Composition indicates a “has-a” relationship between objects. Inheritance, on the other hand, indicates an “is-a” relationship. The Gang of Four would seem to be suggesting that you lean toward (“favor”) the former rather than the latter.
The potentially confusing aspect of this is that the patterns they delineate in the book use inheritance fairly extensively. Why would they recommend against this, and then do it?
Inheritance can be used for two different things:
- To create polymorphism: sub-classes can be exchanged for each other, and can be cast to their base type, hiding their actual type from clients.
- To specialize: sub-classes gain elements from their base class that they can accept or change, creating special versions of whatever the base class does.
What the advice means is that we should shy away from doing the latter, for the most part. If you examine the patterns, you’ll see that inheritance is almost always used as a way of creating interchangeability.
This was also meant to disabuse designers from the notion that inheritance is for reuse. Reuse is better achieved using delegation through an interface, rather than the more intimate connection that inheritance-for-specialization creates.
This is Scott Bain. Visit us at www.netobjectives.com.