Refactoring Remove Middle Man
ProblemA class has too many methods that simply delegate to other objects.
SolutionDelete these methods and force the client to call the end methods directly.
In this technique, we will use the terms from Hide Delegate, which are:
- delegate — the end object that contains the functionality needed by the client
- server — the object to which the client has direct access
There are two types of problems:
The server-class does not do anything itself and simply creates needless complexity. In this case, give thought to whether this class is needed at all.
Every time a new feature is added to the delegate, you need to create a delegating method for it in the server-class. If a lot of changes are made, this will be rather tiresome.
How to Refactor
Create a getter for accessing the delegate-class object from the server-class object.
Replace calls to delegating methods in the server-class with direct calls for methods in 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 ()