Navigation: Appendix B: Dolphin Pattern Book > Miscellaneous Patterns >
Inheritance vs. Composition
Two of the main techniques for re-using code are Class Inheritance and Object Composition.
|•||Class Inheritance defines a new class in terms of an existing class. A subclass inherits both data and protocol from its superclass.|
|•||Object Composition defines a new class as containing an instance of one or more existing classes. This type of class inherits nothing from the objects it contains. This pattern should help you decide which technique to use.|
How do we decide when to use inheritance and when composition is more appropriate?
A simple rule of thumb is that Class Inheritance should be used only if instances of the new class can be used in all situations where the proposed superclass class can currently be used. Class Inheritance not usually appropriate if the subclass needs to stub out behaviour implemented by the superclass. Use Object Composition if instances of the new class do not require the complete protocol of the superclass.
Consider a new class Stack which is implemented as an Array. We can either subclass Stack from Array (class inheritance):
Array variableSubclass: #Stack
or we can use an instance of Array as a data member of Stack (object composition):
Object subclass: #Stack
In this case, it would make more sense to use object composition (the second example). Instances of Stack do not need to inherit the extensive Collection protocol.
The PropertyManager class uses Object Composition. It contains an instance of WeakIdentityDictionary rather than subclassing from WeakIdentityDictionary. As a result, the protocol of PropertyManager is very compact.