Improving classes with interfaces and polymorphism
We’re nearly at the close of this chapter on object-oriented refactoring. However, before we close the chapter, let’s discuss a few places where introducing interfaces and polymorphism can help further improve our code.
Extracting interfaces
At the moment, our CharterFlightInfo
class stores a list of CargoItem
s representing its cargo:
public class CharterFlightInfo : FlightInfoBase { public List<CargoItem> Cargo { get; } = new(); // Other members omitted... }
Each cargo item the charter flight includes must be a CargoItem
or something that inherits from it. For example, if we were to create the HazardousCargoItem
we discussed in the last section and try to store it in the cargo collection, it must inherit from CargoItem
to compile.
In many systems, you don’t want to force people to inherit from your classes if they want to customize the system’s behavior. In these...