# Middle ManFourteen methods, twelve of them one-line forwards. Learn to spot a Middle Man, remove it, balance it against Hide Delegate, and tell it from Proxy, Decorator, Facade and Adapter.

Last lesson, in [Message Chains](/code-smells/message-chains/), we hid every delegate behind a
method. A month later, the box office class has fourteen methods. Twelve of them are a single line:
each one passes the call straight to the venue. Then the venue team adds a feature, finding
accessible seats, and the box office needs a thirteenth forward. A class that mostly passes calls
along is a smell called **Middle Man**. It's the other side of message chains.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows
it section by section, with diagrams and a little extra depth.

{{< lesson-video youtube="ZddDUkNPaOo" title="Middle Man" >}}

## Fourteen methods, twelve forwards

```mermaid {alt="BoxOffice has fourteen methods. Twelve are one-line forwards to Venue, and two, sell and refund, do real work." caption="Fourteen methods, twelve forwards."}
flowchart LR
  B["BoxOffice<br/>14 methods"] -->|"12 one-line forwards"| V["Venue"]
  B --> R["sell, refund<br/>2 real methods"]
  class B c5
  class V c6
  class R good
```

Each forward passes the call straight to the venue: `seatAt`, `sectionFor`, `openingTime`, and nine
more. When the venue grows a new feature, the box office has to grow a matching forward. It's what
happens when "hide the delegate" is applied everywhere without asking whether anyone needed the
hiding.

## A receptionist who only repeats

Picture a receptionist who answers every question the same way. She turns to the colleague beside
her, and repeats your question word for word. The colleague answers, and she repeats the answer back
to you. She never checks anything, decides anything, or adds anything. You could have asked the
colleague yourself. All she added was a hop.

Compare a different receptionist. She checks your name, finds your booking, and hands you a map.
That desk earns its place.

```mermaid {alt="The receptionist analogy mapped onto code: you ask the receptionist, who is the BoxOffice, and she repeats the same question to the colleague, who is the Venue. The answer travels back the same way." caption="The first receptionist adds nothing."}
flowchart TD
  Y["you"] -->|"question"| R["receptionist<br/>BoxOffice"]
  R -->|"same question"| C["colleague<br/>Venue"]
  C -.->|"answer"| R
  R -.->|"same answer"| Y
  class R c5
  class C c6
```

In code, the receptionist is the box office and the colleague is the venue. The course reference
describes a **middle man** as a class that does little more than pass data or calls between two other
classes. It doesn't process, clean or convert what it handles.

## The box office, shown fairly

Here's the box office class. To be fair, it came from a good place. After last lesson, no screen
reaches through it any more.

```java
class BoxOffice {
    private final Venue venue;

    Seat seatAt(String section, int row, int number) {
        return venue.seatAt(section, row, number);
    }

    String sectionFor(Seat seat) {
        return venue.sectionFor(seat);
    }

    LocalTime openingTime() {
        return venue.openingTime();
    }

    // nine more forwards, and refund()

    Receipt sell(Ticket ticket, Payment payment) {
        validate(ticket);
        Receipt receipt = payment.charge(ticket.seatPrice());
        log.recordSale(receipt);
        return receipt;
    }
}
```

Each forward is correct. Each is a single line, with the right arguments, and it hides how the venue
works. Then there's `sell`, which really does something: it validates the ticket, takes the payment
and writes the receipt to the log. So the class has twelve forwards and two methods that do real
work. That ratio is the clue.

## What forwarding costs

1. **Every feature the venue grows needs a new forward.** The box office can't offer what the venue
   can until someone types it in.
2. **A change ripples twice.** Add a parameter to the venue's `seatAt`, and the box office forward
   needs it too.
3. **Every reader pays a hop.** To learn what `openingTime` does, you open the box office, find a
   forward, and open the venue: two files for one answer.
4. **The class looks busy.** Fourteen methods looks like a rich object. But twelve of them are empty.

## How to spot it

1. **The body is one call on a field.**
2. **Same name, same parameters** as the delegate's method. It's a mirror.
3. **One field does all the work**, and most methods touch nothing else.
4. **A new delegate feature means a new method here.**

```java
LocalTime openingTime() { return venue.openingTime(); }
```

## The key insight: a class earns its place

A class earns its place by adding something: a rule, a check, a translation, or a simpler view. Strip
away the forwards, and ask what's left. Here, it's `sell` and `refund`. That's the real class. If a
class only repeats what another class says, the other class can speak for itself.

## Remove Middle Man

The refactoring is called **Remove Middle Man**. It's the inverse of
[Hide Delegate](/code-smells/message-chains/): clients stop going through the box office, and
talk to the venue. Take the seat picker. It asks the box office for a seat, and the box office asks
the venue:

```java
class SeatPicker {
    private final BoxOffice boxOffice;

    Seat pick(String section, int row, int number) {
        Seat seat = boxOffice.seatAt(section, row, number);
        if (seat.isTaken()) {
            throw new IllegalStateException("seat taken");
        }
        return seat;
    }
}
```

Give it the venue directly. The call changes, and nothing else about the seat picker does:

```java
class SeatPicker {
    private final Venue venue;

    Seat pick(String section, int row, int number) {
        Seat seat = venue.seatAt(section, row, number);
        if (seat.isTaken()) {
            throw new IllegalStateException("seat taken");
        }
        return seat;
    }
}
```

Do that for each client, and a forward loses its last caller. Delete it. When a forward has one
caller left, **inline the method** instead: replace the call with the forward's body.

```java
// before
LocalTime opens = boxOffice.openingTime();

// after
LocalTime opens = venue.openingTime();
```

Now the box office is what it should have been: `sell` and `refund`, and nothing else.

```java
class BoxOffice {
    Receipt sell(Ticket ticket, Payment payment) {
        validate(ticket);
        Receipt receipt = payment.charge(ticket.seatPrice());
        log.recordSale(receipt);
        return receipt;
    }

    void refund(Ticket ticket) {
        ticket.refund();
        log.recordRefund(ticket);
    }
}
```

Twelve forwards deleted, nothing lost, and the venue can grow without anyone editing the box office.

```mermaid {alt="Before and after Remove Middle Man. Before: clients call BoxOffice, which forwards twelve calls to Venue. After: clients call Venue directly, and BoxOffice keeps only sell and refund." caption="Clients talk to the venue; the box office keeps its own work."}
flowchart TB
  subgraph before ["Before"]
    direction LR
    C1["Clients"] --> B1["BoxOffice<br/>12 forwards"] --> V1["Venue"]
  end
  subgraph after ["After"]
    direction LR
    C2["Clients"] --> V2["Venue"]
    C3["Sales code"] --> B2["BoxOffice<br/>sell, refund"]
  end
  before ~~~ after
  class B1 bad
  class V1,V2 c6
  class B2 good
```

```mermaid {alt="Class diagram after Remove Middle Man: SeatPicker asks Venue directly for seats. BoxOffice has only sell and refund. Venue offers seatAt, sectionFor and openingTime." caption="The refactored design."}
classDiagram
  class SeatPicker {
    pick(section, row, number) Seat
  }
  class BoxOffice {
    sell(ticket, payment) Receipt
    refund(ticket) void
  }
  class Venue {
    seatAt(section, row, number) Seat
    sectionFor(seat) String
    openingTime() LocalTime
  }
  SeatPicker --> Venue : asks directly
```

## Hide, or remove? The balance

Wait. Last lesson said to hide delegates. This lesson says to remove the middle man. Which is it?
Both are right, and they're **opposite moves**. Hide Delegate takes a class's insides out of the
client's sight. Remove Middle Man puts them back in view. In Fowler's catalog each is the inverse of
the other.

Push too far one way, and clients walk long chains. Push too far the other way, and a class is
nothing but forwards.

```mermaid {alt="A balance between two smells. Too little hiding gives message chains, clients walk long chains. Too much hiding gives a middle man, a class that is only forwards. In between, forward what clients really ask." caption="The right point is in between."}
flowchart LR
  L["too little hiding<br/>Message Chains"] --- M["in between:<br/>forward what<br/>clients really ask"] --- R["too much hiding<br/>Middle Man"]
  class L,R bad
  class M good
```

The right point is in between. Forward what clients really ask: what does my seat cost?
(`ticket.seatPrice()`.) Don't forward everything the venue can do. So hide a delegate when many
clients keep reaching through it for the same question, and remove the middle man when forwards
outnumber real work.

## A second example: the service layer

A layered design often grows a ticket service above the ticket repository:

```java
class TicketService {
    private final TicketRepository repository;

    Ticket find(long id) { return repository.find(id); }
    void save(Ticket ticket) { repository.save(ticket); }
    void delete(Ticket ticket) { repository.delete(ticket); }
}
```

Find, save, delete. Each method passes straight through to the repository, with the same name and the
same argument. Callers could hold the repository themselves. The service adds a layer of boxes, and
no behavior.

Now compare a service that earns it. Cancelling a ticket checks the refund policy, deletes the
ticket, and emails the customer:

```java
void cancel(long id) {
    Ticket ticket = repository.find(id);
    policy.checkRefundable(ticket);
    repository.delete(ticket);
    mailer.sendCancellation(ticket);
}
```

That's the difference. The first class forwards. The second class decides.

## Forwarding with a purpose

Not all forwarding is a smell. Several patterns forward calls on purpose, and each adds something:

| Pattern | Forwards, and also | Lesson |
|---|---|---|
| Proxy | controls access, or delays the work | [Proxy](/patterns/proxy-pattern/) |
| Decorator | adds behavior around the call | [Decorator](/patterns/decorator-pattern/) |
| Facade | offers one simpler interface over many classes | [Facade](/patterns/facade-pattern/) |
| Adapter | translates between two interfaces | [Adapter](/patterns/adapter-pattern/) |
| **Middle Man** | **nothing** | this lesson |

Each forward there has a reason you can name. A middle man has no reason to name. The course
reference says the same: leave a class alone when it follows a design pattern such as Proxy or
Decorator, where delegation is intentional.

## Myth, and when to leave it

One myth to drop: **delegation is bad**. It isn't. Delegation is how objects cooperate. The empty
kind is the smell.

And there is a reason to keep a forward. Remember the event's `seatPrice` method from last lesson?

```java
class Event {
    private final Venue venue;

    double seatPrice(String section, int row, int number) {
        return venue.seatPrice(section, row, number);
    }
}
```

It forwards to the venue. But it keeps the ticket from knowing the venue exists. The course reference
lists this as a case to ignore: an intermediary that reduces unnecessary coupling between two
classes. That forward stays. The test is whether it hides something worth hiding, or only repeats.

```mermaid {alt="Decision flow for a forwarding method. Does the method only forward? If no, it is fine. If yes, does it add something, such as access control, behavior, a simpler interface or translation, or keep a class from knowing a detail? If yes, keep it. If no, remove the middle man, or inline the method if one caller is left." caption="What does this method add?"}
flowchart TD
  Q1{"Does the method<br/>only forward?"}
  Q1 -->|no| F["Fine"]
  Q1 -->|yes| Q2{"Does it add something,<br/>or hide a detail<br/>worth hiding?"}
  Q2 -->|yes| K["Keep it"]
  Q2 -->|no| R["Remove Middle Man<br/>(inline if one caller)"]
  class F,K good
  class R bad
```

So ask of every forward: what does this add? If the answer is nothing, remove it. If the answer is
distance from a detail, keep it.

## Recap

A middle man is a class whose methods mostly just pass calls along. Remove Middle Man, so clients
talk to the delegate directly, and inline the few forwards that remain. Keep forwards that add
something: a proxy, a decorator, a facade, an adapter, or real distance from a detail. Hide Delegate
and Remove Middle Man are opposite moves, so stay somewhere between them.

```mermaid {alt="Recap chain: spot the forwards, Remove Middle Man, inline the few that remain, keep forwards that add something." caption="Forward with a purpose, or don't forward."}
flowchart LR
  A["spot the forwards"] --> B["Remove Middle Man"] --> C["inline the few<br/>that remain"] --> D["keep forwards<br/>that add something"]
  class B,C good
```

Checklist:

- Is a method's whole body one call on a field, with the same name and parameters as the delegate's?
- Do most methods of the class touch only that one field?
- Does every new delegate feature start with a new method here?
- Could clients hold the delegate themselves?
- Does the forward add access control, behavior, a simpler interface, translation, or protection from a detail?

> **Forward with a purpose, or don't forward.**

## Further reading

- [Middle Man](https://refactoring-assistant.github.io/couplers/middle-man), the course's Code Smells Reference.
- Refactoring catalog: [Remove Middle Man](https://refactoring.com/catalog/removeMiddleMan.html),
  [Hide Delegate](https://refactoring.com/catalog/hideDelegate.html),
  [Inline Function](https://refactoring.com/catalog/) (called Inline Method in the first edition).
- Related lessons: [Message Chains](/code-smells/message-chains/) (the partner smell),
  [Proxy](/patterns/proxy-pattern/), [Decorator](/patterns/decorator-pattern/),
  [Facade](/patterns/facade-pattern/), [Adapter](/patterns/adapter-pattern/).
