Wednesday, November 26, 2008

Favor Composition Over Inheritance

Put another way, favor "has-a" over "is-a" relationships.

What's so bad about inheritance?
  • Subclasses are tightly coupled to their base classes. Many times subclasses make assumptions about the context in which a method it overrides is getting called, which means that small implementation changes in the base class can produce unexpected behavior.
  • Dependencies of the subclass are hard-wired making unit testing difficult. One cannot mock a base class of a subclass.
It is definitely fine to inherit from interfaces; it's the concrete implementations that cause all of the problems.

An added benefit of composition relationships is that behavior can be changed at run-time (Strategy Pattern).

1 comment:

  1. I waver on this one. Sure, more than half the patterns in the GOF Design Patterns book can be grouped under the general heading "Favor Composition Over Inheritance." And I wouldn't argue with any of those patterns as responses to the motivations documented in that book. But I also strongly believe in the old axiom, "Faithfully Model Reality."

    If there is a situation where an "is-a" relationship fits naturally - where the abstraction to be a subclass is, and will always be, a specialized form of a more general abstraction - then I say go ahead and use inheritance. Of course, if you have even the slightest doubt regarding the permanence of an is-a relationship (e.g. Los Angeles is a city on the mainland continent of North America), by all means use composition for the flexibility it adds to a design.

    ReplyDelete