Refactoring Hide Delegate


The client gets object B from a field or method of object А. Then the client calls a method of object B.


Create a new method in class A that delegates the call to object B. Now the client does not know about, or depend on, class B.
Hide Delegate - Before
Hide Delegate - After

Why Refactor

To start with, let's look at terminology:

  • delegate — the end object that contains the functionality needed by the client
  • server — the object to which the client has direct access

A call chain appears when a client requests an object from another object, then the second object requests another one, and so on. These sequences of calls involve the client in navigation along the class structure. Any changes in these interrelationships will require changes on the client side.


  • Hides delegation from the client. The less that the client code needs to know about the details of relationships between objects, the easier it is to make changes to your program.


  • If you need to create an excessive number of delegating methods, server-class risks becoming an unneeded go-between, leading to an excess of Middle Man.

How to Refactor

  1. For each method of the delegate-class called by the client, create a method in the server-class that delegates the call to the delegate-class.

  2. Change the client code so that it calls the methods of the server-class.

  3. If your changes free the client from needing the delegate-class, you can remove the access method to the delegate-class from the server-class (the method that was originally used to get the delegate-class).

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 ()