When aiming to achieve the same goals as inheritance, composition is generally favorable.
It's true; I looked it up.
Augie Fackler and Nathaniel Manista gave a mind-blowingly good talk about this at PyCon 2013, which I have been obsessively re-watching with an almost maniacal zeal for the last year.
Don't think it's a good talk? Watch it again.
However, many discussions of preferring composition over inheritance are stratospherically high-level and lack concrete examples. Even the aforementioned fantastic talk is pretty thin in terms of laying out why one would accept things like "structural expression of programs" as a good thing.
I'll be using this stream to collect my ongoing thoughts about inheritance, and trying to build a compendium of specific examples of why it's bad, eschewing the usual stuff about how it's "not flexible" or "binds too tightly" or whatever, as well as techniques for avoiding it. Some of this stuff will of course continue to be high-level, of course, this is a programming-language-level feature of course and therefore extremely abstract.
Inheritance is bad because
Wheel
andTortilla
should not both inherit fromCircle
.– David Reid
One very common problem with class inheritance, of course, is that you don't get anything so clean as Tortilla
and Wheel
inheriting from Circle
. Generally in a large, real-world project, you get Circle
inheriting from both Tortilla
and Wheel
, because you already had a Tortilla
and a Wheel
at the time you discovered you needed a Circle
, and it was so much easier to just do that for now.
So now all Circle
s have numberOfSpokes
and also cornOrFlour
attributes.