# Message ChainsOne line prices a seat through five classes, and a small change breaks six screens. Learn to spot Message Chains, fix them with Hide Delegate or Move Method, and tell them from fluent calls.

A box office screen needs the price of a seat. So it reads it straight off the ticket: the ticket's
event, the event's venue, the venue's seat map, then a seat, and finally its price. Then the venue
team restructures the seat map into sections. One small change, in one class, and six screens stop
compiling. The screens did nothing wrong. They just know too much. That's a smell called **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="MVFNnfWDVNs" title="Message Chains" >}}

## One line, six broken screens

Here is the line:

```java
class BoxOfficeScreen {
    double priceAt(Ticket ticket) {
        return ticket.getEvent().getVenue().getSeatMap()
                .seatAt(ticket.getRow(), ticket.getNumber())
                .price();
    }
}
```

To get a price, the code walks through five classes:

```mermaid {alt="The chain of calls in the box office screen: Ticket, then Event, then Venue, then SeatMap, then Seat, ending in the price. SeatMap is highlighted because it is the class that changes." caption="One line, five classes."}
flowchart TD
  T["Ticket"] -->|"getEvent()"| E["Event"] -->|"getVenue()"| V["Venue"] -->|"getSeatMap()"| M["SeatMap"] -->|"seatAt(...)"| S["Seat"] -->|"price()"| P["price"]
  class T c1
  class E c5
  class V c6
  class M warn
  class S c4
  class P muted
```

The screens did nothing wrong. They just know too much.

## Directions, passed along

Think about asking for directions in a big building. You ask the guard at the gate, and she says,
ask reception. Reception says, try the admin office. And the admin office says, it's on the third
floor.

You get there. But now you depend on every hop. Move the records, or rename an office, and your
whole route is wrong.

```mermaid {alt="The directions analogy mapped onto code: the guard is the Ticket, reception is the Event, the admin office is the Venue and the third floor is the SeatMap. The arrows are the getters getEvent, getVenue and getSeatMap." caption="Each hop is a getter, and the route is the chain."}
flowchart TD
  G["guard<br/>Ticket"] -->|"getEvent()"| R["reception<br/>Event"] -->|"getVenue()"| A["admin office<br/>Venue"] -->|"getSeatMap()"| F["third floor<br/>SeatMap"]
  class G c1
  class R c5
  class A c6
  class F warn
```

In code, each hop is a getter, and the route is a chain. The course reference describes a
**message chain** as data reached through a series of calls, where each call depends on the one
before it.

## The chain, shown fairly

Look at the screen again. To be fair, it's tidy. Every call is a real getter, and it reads like a
sentence. Each class does its job, each getter returns something sensible, and nobody wrote
anything silly.

The problem is what the screen has to know. It knows a ticket has an event, an event has a venue,
and a venue has a seat map: five classes, and the screen is welded to the shape of every one of
them. Nothing is wrong in any single line. The dependency is in the route.

## Why it hurts

Watch what that costs. The venue team splits the seat map into sections. `seatAt` now takes a
section, as well as a row and a number:

```java
class SeatMap {
    private final Map<String, Section> sections;

    Seat seatAt(String section, int row, int number) {
        return sections.get(section).seat(row, number);
    }
}
```

The screen from the hook breaks. So do the mobile app, the refund desk, the upgrade dialog, the
ticket printer and the sales report.

```mermaid {alt="A change to SeatMap, seatAt now takes a section, breaks six screens: box office, mobile app, refund desk, upgrade dialog, ticket printer and sales report, because each has the same route copied into it." caption="One change inside the venue, six broken screens."}
flowchart LR
  M["SeatMap.seatAt<br/>now takes a section"] --> A["box office"]
  M --> B["mobile app"]
  M --> C["refund desk"]
  M --> D["upgrade dialog"]
  M --> E["ticket printer"]
  M --> F["sales report"]
  class M warn
  class A,B,C,D,E,F bad
```

Six screens, with the same route copied into each. Not one of them cares about sections. They only
wanted a price. That's the first cost: a change inside the venue ripples outward, to everyone who
walked through it. It's the same shape as [Shotgun Surgery](/code-smells/shotgun-surgery/),
reached through someone else's structure.

The second cost is testing. To check one price, you have to build an event, a venue, a seat map and
a seat.

Software people call the idea behind all this the **Law of Demeter**, or the principle of least
knowledge: an object should talk to its close neighbours, not to strangers. It was proposed at
Northeastern University around the end of 1987.

## How to spot it

1. **A run of dots where each call hands back a different kind of object**, like
   `a().b().c().d()`.
2. **The same route in many places.** Search for `getVenue().getSeatMap()` and count the results.
3. **The chain in disguise.** A local variable for the event, one for the venue, one for the seat
   map:

```java
Event event = ticket.getEvent();
Venue venue = event.getVenue();
SeatMap seatMap = venue.getSeatMap();
```

It's the same chain, split across lines. The screen still knows every hop.

## The key insight: stop navigating, ask

So here is the insight. The screen isn't asking for a price. It's *navigating*: it knows the route
through other objects' structure. The fix is to stop navigating, and ask. Ask your nearest
neighbour, the ticket, for the price. Let it find out how.

A class should know its neighbours, and nothing past them.

## Hide Delegate

The refactoring is called **Hide Delegate**. The ticket gets a new method, `seatPrice`, that does
the walking for its callers. But the ticket doesn't walk the whole route. It asks only its event,
and the event asks only its venue. The venue is the one place that knows about the seat map.

```java
class Ticket {
    double seatPrice() {
        return event.seatPrice(section, row, number);
    }
}

class Event {
    private final Venue venue;

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

class Venue {
    private final SeatMap seatMap;

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

Now the screen makes one call: it asks the ticket for its seat price.

```java
double price = ticket.seatPrice();
```

At the scale of a whole subsystem, this is the idea behind the [Facade](/patterns/facade-pattern/)
pattern: one simple front, so clients don't have to learn the structure behind it.

Last, the hops lose their getters. Remove the getter for the venue, or make it private, so nobody
can walk the old route again. Now the venue team splits the seat map again, and exactly one method
changes. The six screens never notice.

```mermaid {alt="Before and after Hide Delegate. Before: the box office screen links to Ticket, Event, Venue and SeatMap directly. After: the screen links only to Ticket, and each class links only to the next one." caption="Before: four links from the screen. After: one."}
flowchart TB
  subgraph before ["Before"]
    direction LR
    S1["Screen"] --> T1["Ticket"]
    S1 --> E1["Event"]
    S1 --> V1["Venue"]
    S1 --> M1["SeatMap"]
  end
  subgraph after ["After"]
    direction TB
    S2["Screen"] --> T2["Ticket"] --> E2["Event"] --> V2["Venue"] --> M2["SeatMap"]
  end
  before ~~~ after
  class S1,T1,E1,V1,M1 bad
  class S2,T2,E2,V2,M2 good
```

```mermaid {alt="Class diagram after Hide Delegate: BoxOfficeScreen asks Ticket for seatPrice. Ticket asks Event, Event asks Venue, and Venue asks SeatMap for the seat. Each class only talks to the next one." caption="Each class talks only to its neighbour."}
classDiagram
  class BoxOfficeScreen
  class Ticket {
    seatPrice() double
  }
  class Event {
    seatPrice(section, row, number) double
  }
  class Venue {
    seatPrice(section, row, number) double
  }
  class SeatMap {
    seatAt(section, row, number) Seat
  }
  BoxOfficeScreen --> Ticket : asks
  Ticket --> Event
  Event --> Venue
  Venue --> SeatMap
```

## Move the work to the data

Sometimes a chain means the work lives in the wrong class. Here, a screen decides whether a ticket
was discounted:

```java
boolean isDiscounted(Ticket ticket) {
    double list = ticket.getEvent().getVenue().getSeatMap()
            .seatAt(ticket.getSection(), ticket.getRow(),
                    ticket.getNumber()).price();
    return ticket.getPaid() < list;
}
```

It walks to the seat price, and compares it with what the buyer paid. But what the buyer paid
belongs to the ticket. So extract the decision into a method, and move it onto the ticket. That's
**Extract Method**, then **Move Method**:

```java
class Ticket {
    boolean isDiscounted() {
        return paid < seatPrice();
    }
}
```

The data and the decision now sit together. The screen asks a yes-or-no question, and gets a
yes-or-no answer: `ticket.isDiscounted()`.

## A second example: the refund desk

Here is one with a twist. At the refund desk, the code doesn't read anything. It changes
something:

```java
ticket.getOrder().getBuyer().getWallet().credit(ticket.getPaid());
```

It goes from the ticket to its order, then the order's buyer, then the buyer's wallet, and then it
pays the money in. So the refund desk knows that customers have wallets. It shouldn't even know
wallets exist.

Same fix. The ticket gets a `refund` method. So does the order. And only the customer touches the
wallet:

```java
// refund desk
ticket.refund();

class Ticket {
    void refund() { order.refund(paid); }
}

class Order {
    void refund(double amount) { buyer.refund(amount); }
}

class Customer {
    void refund(double amount) { wallet.credit(amount); }
}
```

The desk says what it wants, a refund. Each neighbour decides how.

## Not every chain of dots

Is every chain of dots a message chain? No. Look at this stream pipeline:

```java
List<String> titles = events.stream()
        .filter(e -> e.isOnSale())
        .map(Event::getTitle)
        .toList();
```

Each call hands back a stream. The code never walks through anyone's structure. It keeps working on
the same kind of thing. The Java API describes `filter` and `map` as intermediate operations that
return a stream. Builders work the same way: each call returns the builder itself, so the calls
chain, by design.

So count the types, not the dots. It's a smell only when each dot steps into a different object's
insides.

| Chain | Types along the way | Message chain? |
|---|---|---|
| `events.stream().filter(…).map(…).toList()` | a stream, a stream, a stream | no |
| `builder.event(e).section(s).build()` | the builder, the builder, the builder | no |
| `ticket.getEvent().getVenue().getSeatMap()` | Ticket, Event, Venue, SeatMap | yes |

[Feature Envy](/code-smells/feature-envy/) is a close cousin. Envy is a method using another
class's data more than its own. A chain is often the route it takes to reach that data, and the fix
for both is to move behavior to where the data lives.

## When to leave it alone

When is it fine to leave a chain alone? When the structure is stable, and public by design.

```java
DayOfWeek day = event.getStart().toLocalDate().getDayOfWeek();
```

Only the first hop is ours. Java's date types are documented, public, and not about to change. The
same goes for plain data objects that exist to be read, like a parsed report.

And there is a case where the fix backfires. Hide every hop, and a class can end up as nothing but
forwards:

```mermaid {alt="A decision flow. Does the call walk through different types? If no, it is fine (a fluent call). If yes, is that structure stable and public by design? If yes, leave it. If no, would hiding it only add forwards? If yes, leave it, because that creates a Middle Man. If no, use Hide Delegate or Move Method." caption="When to refactor a chain."}
flowchart TD
  Q1{"Does the call walk through<br/>different types?"}
  Q1 -->|no| F["Fine: a fluent call"]
  Q1 -->|yes| Q2{"Is the structure stable<br/>and public by design?"}
  Q2 -->|yes| L["Leave it"]
  Q2 -->|no| Q3{"Would hiding it only<br/>add forwards?"}
  Q3 -->|yes| M["Leave it: Middle Man ahead"]
  Q3 -->|no| H["Hide Delegate or Move Method"]
  class F,L good
  class M warn
  class H c1
```

That's the next smell, [Middle Man](/code-smells/middle-man/), the other side of message
chains. The course reference makes the same point: skip the fix if resolving the chain would cause
a Middle Man.

## Recap

A message chain is a client walking through other objects to reach what it needs. Hide the route
with Hide Delegate, or extract the work and move it next to its data. Leave fluent calls and stable
structures alone, and stop hiding when a class only forwards.

```mermaid {alt="Recap chain: spot the route, Hide Delegate, Extract and Move Method, leave fluent and stable chains alone." caption="Ask your neighbour, not your neighbour's neighbour."}
flowchart LR
  A["spot the route"] --> B["Hide Delegate"] --> C["Extract + Move Method"] --> D["leave fluent and<br/>stable chains"]
  class B,C good
```

Checklist:

- Does one line walk through several different types?
- Is the same route copied into many places, or hidden in local variables?
- Would a change inside the middle of the route break clients that don't care about it?
- Can the nearest neighbour answer the question for you?
- Would hiding the route only create a class full of forwards?

> **Ask your neighbour, not your neighbour's neighbour.**

## Further reading

- [Message Chains](https://refactoring-assistant.github.io/couplers/message-chains), the course's Code Smells Reference.
- Refactoring catalog: [Hide Delegate](https://refactoring.com/catalog/hideDelegate.html),
  [Remove Middle Man](https://refactoring.com/catalog/removeMiddleMan.html), and
  [Move Function and Extract Function](https://refactoring.com/catalog/) (called Move Method and Extract Method in the first edition).
- [Law of Demeter](https://en.wikipedia.org/wiki/Law_of_Demeter) (principle of least knowledge).
- [java.util.stream.Stream](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/stream/Stream.html) in the Java SE 17 API.
- Related lessons: [Feature Envy](/code-smells/feature-envy/),
  [Shotgun Surgery](/code-smells/shotgun-surgery/), [Facade](/patterns/facade-pattern/),
  and the partner smell, [Middle Man](/code-smells/middle-man/).
