Building features through inheritance and composition

As noted earlier in the Liskov Substitution Principle section, there are two general ways to add features to a class definition:

  • Inheritance to extend a class by creating a subclass
  • Composition of a new class from one or more other classes

In general, these choices are always present. Every object-oriented design decision involves choosing between inheritance and composition.

To make the decision more nuanced, Python allows multiple inheritance. While combining multiple mixing classes is partially a kind of inheritance, it is more fundamentally an exercise in composition. 

The LSP can lead to avoiding inheritance in favor of composition. The general suggestion is to reserve inheritance for those situations where the child class can fully replace the parent class. When features are changed in some way to create a child that is not a direct replacement for the parent, then composition may be more appropriate.

Consider the consequences of adding some features to the Hand class shown earlier. Here are two examples: 

  • The Hand3 subclass extended the Hand class by introducing an additional method. This extension is compatible with the superclass, and Hand3 can be used as a substitute for Hand. This seems to be a sensible extension via inheritance.
  • The FancyDealer4 class introduced a new class composed of a new method making use of the DominoBoneYard3 class. This class introduced a profound change to the hand_iter() method; the change was not trivially compatible with the superclass.

There are yet more composition techniques available in Python. In Chapter 9, Decorators and Mixins – Cross-cutting Aspects, we addressed two additional composition techniques. We'll look at some other patterns of class composition in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset