Pattern: Inheritance vs. Composition


Context

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.

Solution

Class Inheritance should be used only if instances of the new class can be used in all situations where the existing class can be used. Class Inheritance not inappropriate 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 protocol of the superclass.

Example

Consider a new class Stack which is implemented as an Array. We can either subclass Stack from Array (class inheritance):

Array variableSubclass: #Stack
        instanceVariableNames: ''
        classVariableNames: ''
        poolDictionaries: ''

or we can use an instance of Array as a data member of Stack (object composition):

Object subclass: #Stack
        instanceVariableNames: 'array'
        classVariableNames: ''
        poolDictionaries: ''

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.

Known Uses

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.

Related Patterns