Friday, April 08, 2005

Inheritance

For some reason, inheritance has been under attack recently. One source that people frequently cite is an article by Allen Holub, called "Why extends is evil". Allen has been around for long enough to have acquired the status of knowing what he is talking about. I remember reading his articles in DDJ, myself. That makes it more surprising that his article totally misses the point of inheritance. Let's look at his example.
Allen extends Java's ArrayList class to make it behave like a stack. Er, OK, but then he points out that actually his nice new Stack class has some flaws:

Stack a_stack = new Stack();
a_stack.push("1");
a_stack.push("2");
a_stack.clear();

Allen rightly points out that by calling clear() on his stack, you leave it in disarray. Ah, but that can be fixed by overriding the all of ArrayList's methods that would subvert his lovely Stack class..Oh, but that means that we have to override so much that we would be better off just inheriting the interface, he writes.

Umm, I think we just hit the core of Allen's problem. By using extends, Allen is telling us that he believes that Stack is-a ArrayList. Yet almost immediately afterwards, he tells us that his Stack class breaks when you try to use ArrayList behaviour on it. In other words, a Stack does not have an is-a relationhip with ArrayList. And Allen should know that using extends in a situation where there is no is-a relationship is just plain wrong.

So why is Allen trying to mislead us? Can it be that Allen has never heard of one of the basic principles of OOD? I doubt it.Is Allen just pulling an Apriil Fools joke on us? No, the article date was August 1, not April 1. Can it be that his work as a consultant has led him into selling voodo and black-magic to his clients? Perish the thought. Just stirring up controversy in advance for his forthcoming book. What a cynical idea.

If he had written that "using extends without an is-a relationship" is evil, it would be easier to agree with him. I don't know what motives led him to write such nonsense, but please just politely ignore it. Inheritance is fine when it is properly used. If you don't know when inheritance is appropriate, go and do some homework (try Googling on Liskov Substitution Principle as a start).

Category: ,

0 Comments:

Post a Comment

<< Home