Refactoring Replace Delegation with Inheritance

Problem

A class contains many simple methods that delegate to all methods of another class.

Solution

Make the class a delegate inheritor, which makes the delegating methods unnecessary.
Before
Replace Delegation with Inheritance - Before
After
Replace Delegation with Inheritance - After

Why Refactor

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.

Benefits

  • 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

  1. Make the class a subclass of the delegate class.

  2. Place the current object in a field containing a reference to the delegate object.

  3. 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.

  4. Replace all references to the delegate field with references to the current object.

  5. 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...

Live Example

First time here? No worries!

Everything is quite simple. This example is like video (but much cooler):

  1. After pressing the Play button, you will see floating messages, which will guide you through the example. You can proceed by clicking on them.
  2. You can fast-forward or return to previous steps by pressing arrow buttons on the left.
  3. Also, you can take a look at the code diff window, which will show what has changed in code during the example ()
  4. To check the code for errors, you can press "Compile and test" button ()