The Pain of Inheritance
April 19, 2004 · 12 Comments
When programmers first learn OOP, they tend to overuse inheritance - they see it everywhere and often end up with deeply-nested inheritance trees. This is a Bad Thing. In the real world, inheritance is actually fairly rare because inheritance represents the "is-a" relationship and most real world relationships between entities are more "has-a" than "is-a". Some languages make inheritance more appealing than others. C++ forces you to explicitly declare methods as virtual in order to create the polymorphic behavior associated with inheritance but, on the other hand, encourages you to inherit left, right and center by supporting multiple inheritance. Java proudly eschews that technique but makes all methods virtual by default thus encouraging overuse of inheritance in a different way. Ted Neward mentioned Smalltalk recently (see my earlier blog entry) as a context where inheritance is the hammer for all problems, and in two further posts, he takes Cedric and Bo to task for defending the inheritable-by-default position. Having programmed extensively in both C++ and Java (as well as some Smalltalk), I think I'd side with Ted on this issue because it is harder to write good base classes than it is to write good leaf classes and, in my experience, most classes are not base classes - so it's better to protect the majority and inconvenience the minority.