Refactoring Replace Inheritance with Delegation
ProblemYou have a subclass that uses only a portion of the methods of its superclass (or it's not possible to inherit superclass data).
SolutionCreate a field and put a superclass object in it, delegate methods to the superclass object, and get rid of inheritance.
Replacing inheritance with composition can substantially improve class design if:
- Your subclass violates the Liskov substitution principle, i.e., if inheritance was implemented only to combine common code but not because the subclass is an extension of the superclass.
- The subclass uses only a portion of the methods of the superclass. In this case, it is only a matter of time before someone calls a superclass method that he or she was not supposed to call.
In essence, this refactoring technique splits both classes and makes the superclass the helper of the subclass, not its parent. Instead of inheriting all superclass methods, the subclass will have only the necessary methods for delegating to the methods of the superclass object.
A class does not contain any unneeded methods inherited from the superclass.
Various objects with various implementations can be put in the delegate field. In effect you get a Strategy design pattern.
- You have to write many simple delegating methods.
How to Refactor
Create a field in the subclass for holding the superclass. During the initial stage, place the current object in it.
Change the subclass methods so that they use the superclass object instead of
For methods inherited from the superclass that are called in the client code, create simple delegating methods in the subclass.
Remove the inheritance declaration from the subclass.
Change the initialization code of the field in which the former superclass is stored by creating a new object.
Tired of reading?
No wonder, there are 7 hours worth of the text on this website.
Try out something different. We've just launched the interactive learning course on refactoring. It has more content and much more fun than a boring text.Learn more...
Everything is quite simple. This example is like video (but much cooler):
- After pressing the Play button, you will see floating messages, which will guide you through the example. You can proceed by clicking on them.
- You can fast-forward or return to previous steps by pressing arrow buttons on the left.
- Also, you can take a look at the code diff window, which will show what has changed in code during the example ()
- To check the code for errors, you can press "Compile and test" button ()