Techniquecore
Remove middle man
Also called remove middleman.
When a class does little but forward calls to an object it holds, let clients call that object directly and delete the forwarding methods; the inverse of Hide Delegate.
- Family
- refactoring
- Intent
- Let clients talk to the object that does the work when the class in between only forwards.
- Also called
- Remove Middleman
Purpose
Hide Delegate puts a forwarding method on a class so that clients do not reach through it. Each feature of the delegate that clients use needs one such method. As clients use more features, the class fills with methods that only forward, and it becomes a Middle Man.1
Remove middle man undoes that. The class gives clients the delegate, clients call the delegate directly, and the forwarding methods go. The catalogue card is Hide Delegate run backwards: aPerson.manager becomes aPerson.department.manager again.2 The first edition has the refactoring under the same name.3
The two refactorings move the same line in two directions. The book says that the right amount of hiding is hard to find, and that it changes as the system changes; the pair lets you move the line when it does.1
Steps
- Run the tests and see them pass.
- Give the server class a getter for the delegate.1
- For each client call to a forwarding method, replace it with a call through the getter to the delegate. Test after each.
- When no client calls a forwarding method, delete it, and test.
You can keep some forwarding methods. If one of them is used by many clients and hides a real choice, it can stay.
Example
An account forwards five methods to its ledger. Clients use all of them, and the account adds nothing. After the refactoring, clients get the ledger from the account and call it.
import assert from "node:assert/strict";
class Ledger {
#entries = [];
add(day, cents) { this.#entries.push({ day, cents }); }
balance() { return this.#entries.reduce((s, e) => s + e.cents, 0); }
count() { return this.#entries.length; }
since(day) { return this.#entries.filter((e) => e.day >= day); }
}
// Before: every method of the account forwards to the ledger.
class AccountBefore {
#ledger = new Ledger();
add(day, cents) { this.#ledger.add(day, cents); }
balance() { return this.#ledger.balance(); }
count() { return this.#ledger.count(); }
since(day) { return this.#ledger.since(day); }
}
// After: the account owns the ledger and gives it out.
class Account {
#ledger = new Ledger();
constructor(owner) { this.owner = owner; }
get ledger() { return this.#ledger; }
}
const a = new Account("Ana");
const b = new AccountBefore();
for (const [day, cents] of [[1, 500], [3, -120], [9, 40]]) {
a.ledger.add(day, cents);
b.add(day, cents);
}
assert.equal(a.ledger.balance(), b.balance());
assert.equal(a.ledger.count(), 3);
assert.deepEqual(a.ledger.since(3), b.since(3));
console.log("remove middle man: tests pass");
remove middle man: tests pass
The account keeps its own job, the owner. When the ledger gets a method, clients can use it at once, and the account does not change.
| Language | What the example shows |
|---|---|
| JavaScript | an account that gives out its ledger, as above |
| Python | the same change, with a property for the delegate |
| Java | the same change, with a getter, as the IntelliJ action leaves it |
| Go | the same change, where the forwarding methods go and an exported field takes their place |
class Ledger:
def __init__(self):
self._entries: list[tuple[int, int]] = []
def add(self, day: int, cents: int) -> None:
self._entries.append((day, cents))
def balance(self) -> int:
return sum(c for _, c in self._entries)
def since(self, day: int) -> list[tuple[int, int]]:
return [e for e in self._entries if e[0] >= day]
class Account:
"""After: the account gives out its ledger, and the forwarding methods are gone."""
def __init__(self, owner: str):
self.owner = owner
self._ledger = Ledger()
@property
def ledger(self) -> Ledger:
return self._ledger
a = Account("Ana")
for day, cents in [(1, 500), (3, -120), (9, 40)]:
a.ledger.add(day, cents) # before: a.add(day, cents)
assert a.ledger.balance() == 420 # before: a.balance()
assert a.ledger.since(3) == [(3, -120), (9, 40)]
assert not hasattr(a, "balance")
print("remove middle man: tests pass")
remove middle man: tests pass
import java.util.ArrayList;
import java.util.List;
public class Main {
record Entry(int day, long cents) {}
static class Ledger {
private final List<Entry> entries = new ArrayList<>();
void add(int day, long cents) { entries.add(new Entry(day, cents)); }
long balance() { return entries.stream().mapToLong(Entry::cents).sum(); }
List<Entry> since(int day) { return entries.stream().filter(e -> e.day() >= day).toList(); }
}
// After: a getter for the delegate in place of one forwarding method per feature.
static class Account {
private final String owner;
private final Ledger ledger = new Ledger();
Account(String owner) { this.owner = owner; }
String owner() { return owner; }
Ledger getLedger() { return ledger; }
}
public static void main(String[] args) {
Account a = new Account("Ana");
a.getLedger().add(1, 500);
a.getLedger().add(3, -120);
a.getLedger().add(9, 40);
if (a.getLedger().balance() != 420) throw new AssertionError("balance");
if (a.getLedger().since(3).size() != 2) throw new AssertionError("since");
System.out.println("remove middle man: tests pass");
}
}
remove middle man: tests pass
package main
import "fmt"
type Entry struct {
Day int
Cents int64
}
type Ledger struct{ entries []Entry }
func (l *Ledger) Add(day int, cents int64) { l.entries = append(l.entries, Entry{day, cents}) }
func (l *Ledger) Balance() int64 {
var s int64
for _, e := range l.entries {
s += e.Cents
}
return s
}
// After: the Account methods that only forwarded are deleted,
// and the ledger is an exported field that clients use directly.
type Account struct {
Owner string
Ledger Ledger
}
func main() {
a := Account{Owner: "Ana"}
a.Ledger.Add(1, 500) // before: a.Add(1, 500)
a.Ledger.Add(3, -120)
a.Ledger.Add(9, 40)
if got := a.Ledger.Balance(); got != 420 {
panic(got)
}
fmt.Println("remove middle man: tests pass")
}
remove middle man: tests pass
When to use
- Most methods forward. When about half of the methods of a class only delegate, the book names this refactoring as the fix for Middle Man.1
- The forwarding grows with each feature. If each change to the delegate needs a change to the server too, the server is in the way.
- After Hide Delegate went too far. The line between the two refactorings moves; this one moves it back.
Pitfalls
Undoing a needed hiding. If the server may later get the value from somewhere else, the forwarding method protected the clients from that change. Removing it brings back the Message Chains that Hide Delegate removed.
A shared delegate. Giving out the delegate also gives clients the power to change it. If the server keeps rules about the delegate's state, a client can now break them. Give out a read-only view, or keep the methods that change state.
Partial removal. If some clients call the server and some call the delegate, readers see two ways to do the same thing. Finish the change, or keep a clear rule for which methods stay.
Tools that do it
IntelliJ IDEA has a Remove Middleman action. It "lets you replace all calls to delegating methods in a class with the equivalent calls directly to the field delegated to".4 You place the caret on the delegating field and choose the methods to inline, and the action adds a getter for the field.4
References
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 7, Encapsulation, Remove Middle Man, motivation and mechanics; Chapter 3, Bad Smells in Code, Middle Man
- Martin Fowler, Catalog of Refactorings, Remove Middle Man, the entry; inverse of Hide Delegate
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 7, Moving Features Between Objects, Remove Middle Man
- IntelliJ IDEA documentation, Remove middleman, the introduction; Run the Remove Middleman refactoring
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 2TNNPC Edit this page History Report an error Markdown