You should always be very leery of any article that contains the words "considered evil" in its title. This article, where Allen Holub is unconvincingly trying to make a case that inheritance is evil, is no exception.
There is a well-known phenomenon in the publishing industry pertaining to sensationalism. Whenever you want to write something that will get the attention of your readers, a simple technique is to pick a popular opinion and explain why everyone is wrong about it.
Holub has been using this trick in the past to get readership (like when he said that getters and setters were… uh, evil) but while it would be easy to attack this article on the form, let’s take a look at what he is actually saying.
Allen mentions the fragile base class problem as one of the reasons why you should avoid inheritance altogether. This is a very well-known problem in the OO circles and C++ programmers have been aware of it for more than ten years. The problem is… Allen doesn’t understand it.
To illustrate, Allen uses the example of a Stack class that uses a List as its underlying implementation and he notices that calling clear() on this object will clear only the base class and not the derived one. Fair enough, that’s a good point. But this is *not* the fragile base class problem. What’s interesting is that Allen does give the right description of this problem a few lines above:
Base classes are considered fragile because you can modify a base class in a seemingly safe way, but this new behavior, when inherited by the derived classes, might cause the derived classes to malfunction.
and then he proceeds to demonstrate something totally different. Ahem.
What’s overall disturbing with this article, and with the way Holub approaches problems in general, is the tendency to make sweeping statements. Allen demolishes inheritance by showing a very poor example of inheritance. Someone who would implement a Stack by
- Using a List as the underlying implementation
- Inheriting List instead of delegating to it
is clearly a beginner in object-oriented programming. Nothing that a good book won’t fix. But no, instead of just observing this fact, Allen is trying to make a case that inheritance should be banned altogether. As I read through his articles, it’s pretty clear to me that whatever he is trying to do, he is using the wrong language. How about Lisp instead?
Some of his points are worth making, though, like the emphasis on interfaces. Now, there is a valid fight and it is important to raise every programmer’s awareness to the importance of interface programming.
We all know that inheritance can be abused, but isn’t it so for every feature of every language on the planet? Instead of giving in to simple sensationalism, how about studying the pros and cons of inheritance and trying to educate your readers objectively?
This kind of article would be understandable in a personal weblog, but I expect better from Javaworld.