Wednesday, November 26, 2008

Favor Composition Over Inheritance

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

What's so bad about inheritance?
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).

Labels: ,

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.
Post a Comment

Subscribe to Post Comments [Atom]

<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]