Effective use of abstract classes
Posted in Software on July 28th, 2009 by Jan Willem Tulp – Be the first to commentEvery now and then I run into code where use of abstract classes are not always as optimal as can be. The thing at hand here is reuse of common functionality. There are at least two common ways to reuse common functionality:
- calling methods in an abstract superclass
- calling methods that are delegated to some other class (not a superclass)
Even though both options may have the same final result, I believe that one option is better suited for some situations, and the other for other situations. Notice that when you are calling methods in an abstract superclass, the direction is up: from the subclass to the superclass. In many cases the subclass does the heavy work, and reuses some common functionality from the superclass.
Now the power of abstract super classes is to use the Template Method design pattern. Instead of doing the heavy work in subclasses, you do the heavy work in the abstract class itself, you define some abstract methods that must be implemented by subclasses. These abstract methods are the specifics that differ for each subclass. This way, the direction is more or less down: from the abstract class you want to get something from a subclass that is specific for this subclass, even though the abstract doesn’t have to be aware of the exact subclass. The subclass just has to comply with the signature of the abstract methods defined in the abstract class.
When you just need some reusable functionality, I prefer using delegation instead of using an abstract class. This way the classes become more loosely-coupled, and the class with the delegated functionality can be used by more classes than just a subclass of some abstract class.
So, recap:
- let abstract classes do the heavy work, and have subclasses implement specifics that will be used by an abstract class
- delegate common behavior to a separate class if you just want to reuse some functionality
Tip: a ‘code-smell’ that may indicate that you’d better use delegation instead of an abstract class: if your abstract class does not contain any abstract methods, your abstract class is probably only there so that subclasses can reuse its functionality. In that case: use delegation!



