Hide Delegate
Encapsulate a delegate object to reduce dependencies.
“A client is calling a method of an object of one of your fields.” – Martin Fowler
Law of Demeter support.
graph LR
A[Client] -->|Calls| B[Server]
B -->|Delegates| C[Delegate]
When to apply (Smells)
- Message Chains: Client calling
a.getB().getC().doIt().
Motivation
- Encapsulation: The client shouldn’t need to know that
BusesCto do the job. - Low Coupling: Changes to
Cwon’t ripple to the Client.
Mechanics (Steps)
- Create a method on the Server class that delegates the call to the Delegate.
- Change the client to call the Server method.
Explanation
Problem
A client calls class A, gets object B, and then calls a method on B.
person.department().manager()
Solution
Create a new method in class A that delegates the call to object B.
person.manager()
Real world analogy
You want to talk to the mechanics. You don’t walk into the garage; you talk to the service desk (Hide Delegate), and they talk to the mechanic.
Pros and Cons
| Pros | Cons |
|---|---|
Comparison
- Inverse Refactoring: Remove Middle Man.
Code example
Typescript
Before
After
PHP
Before
After