Refactoring Replace Delegation with Inheritance
ProblemA class contains many simple methods that delegate to all methods of another class.
SolutionMake the class a delegate inheritor, which makes the delegating methods unnecessary.
Delegation is a more flexible approach than inheritance, since it allows changing how delegation is implemented and placing other classes there as well. Nonetheless, delegation stop being beneficial if you delegate actions to only one class and all of its public methods.
In such a case, if you replace delegation with inheritance, you cleanse the class of a large number of delegating methods and spare yourself from needing to create them for each new delegate class method.
- Reduces code length. All these delegating methods are no longer necessary.
When Not to Use
Do not use this technique if the class contains delegation to only a portion of the public methods of the delegate class. By doing so, you would violate the Liskov substitution principle.
This technique can be used only if the class still does not have parents.
How to Refactor
Make the class a subclass of the delegate class.
Place the current object in a field containing a reference to the delegate object.
Delete the methods with simple delegation one by one. If their names were different, use Rename Method to give all the methods a single name.
Replace all references to the delegate field with references to the current object.
Remove the delegate field.
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 ()