In the last few months, the mantra "favor composition over inheritance" seems to have sprung up out of nowhere and become almost some sort of meme within the programming community.  And every time I see it, I'm a little bit mystified.  It's like someone said "favor drills over hammers."  In my experience, composition and inheritance are two different tools with different use cases, and treating them as if they were interchangeable and one was inherently superior to the other makes no sense.

Also, I never see a real explanation for why inheritance is bad and composition is good, which just makes me more suspicious.  Is it supposed to just be accepted on faith?  Liskov substitution and polymorphism have well-known, clear-cut benefits, and IMO comprise the entire point of using object-oriented programming, and no one ever explains why they should be discarded in favor of composition.

Does anyone know where this concept comes from, and what the rationale behind it is?

Though I think I've heard composition-vs-inheritance discussions long before GoF, I can't put my finger on a specific source. Might have been Booch anyway.

<rant>

Ah but like many mantras, this one has degenerated along typical lines:


it is introduced with a detailed explanation and argument by a well-respected source who coins the catch-phrase as a reminder of the original complex discussion
it is shared with a knowing part-of-the-club wink by a few in-the-know for a while, generally when commenting on n00b mistakes
soon it is repeated mindlessly by thousands upon thousands who never read the explanation, but love using it as an excuse not to think, and as a cheap and easy way to feel superior to others
eventually, no amount of reasonable debunking can stem the "meme" tide - and the paradigm degenerates into religion and dogma.


The meme, originally intended to lead n00bs to enlightenment, is now used as a club to bludgeon them unconscious.

Composition and inheritance are very different things, and should not be confused with each other. While it is true that composition can be used to simulate inheritance with a lot of extra work, this does not make inheritance a second-class citizen, nor does it make composition the favorite son. The fact that many n00bs try to use inheritance as a shortcut does not invalidate the mechanism, and almost all n00bs learn from the mistake and thereby improve.

Please THINK about your designs, and stop spouting slogans.

</rant>
