Thou Shalt Not Inherit
Alan Holub is back to writing again. He's posted a piece
"Why extends is evil" in preview of his upcoming book on Design Patterns.
Earlier I wrote about
getting rid of classes which is related. I mentioned static inheritance as being problematic and sighted is as one reason to get rid of classes. But let's explore in a little bit more detail what Holub has to say about getting rid of inheritance.
Holub actually talks about getting rid of
implementation inheritance, a practice most skilled practitioners have accepted. His arguments are:
Losing Flexibility. Every should already be familiar with the advantages of using interfaces as opposed to concrete classes.
Coupling. He always declares member variables private, using protected is plain evil.
Fragile Base Class Problem. He writes about the all too common example of creating a stack by inheriting from a list. Then he proposes the usual solution, use delegation instead.
In the end he sumarizes that the reason why so many people have bad habits is because of the accursed microsoft MFC libraries.
There's nothing really new here from what most people already know. However, what's refreshing is the hard line stance that he takes. Inheritance exists, and most often than not we are all seduced into using it. The rule of thumb then is, never, ever use implementation inheritance.
However, there's one place I seem to be using inheritance alot lately. It just seems unavoidable, I'm working with a library that wasn't designed to be extensible. Since I want to avoid changing the original code, the only pleasant way of modifying it is to inherit from the original classes. In methods where "new" is used (note: new should also be considered harmful) I override these methods, copy and paste the original method, but replace the allocation with my class that's inherited from the original. It's not very elegant!
But, could I do this with AspectJ instead? Well new can be intercepted and introduction and advise is as powerful as inheritance. The only difference is that you still have one class instead of two classes. That is with inheritance a new class is derived from an old to do the extension. With aspects, the number of classes are preserved. However, that doesn't seem to be a problem, if you use a cflow pointcut then you can do different things depending on context.
Two things are immediately obvious when you use aspects, the first is that you reduce the proliferation of classes, the second is that you can modularize all this "hacking" into a single aspect.
In summary, if you absolutely need to use inheritance just don't. Aspects seem to provide a better alternative.
Created by
admin
Last modified
2003-08-04 11:16 AM