Refactoring Hide Delegate
ProblemThe client gets object B from a field or method of object А. Then the client calls a method of object B.
SolutionCreate 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.
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
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.
Change the client code so that it calls the methods of the server-class.
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...
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 ()