Skip to content

Message Chains

Message chains force a caller to walk a path like a.getB().getC().getD(), so any change to that object graph breaks code far away.

6 min readCode smellCoupling

A message chain is a call like booking.getDesk().getFloor().getBuilding().getTimezone(). The caller wants one fact. To get it, it has to know every hop between where it starts and where that fact lives. Each dot is a dependency. The caller now relies on a booking having a desk, a desk having a floor, a floor belonging to a building, and the building storing the timezone itself. If any link changes, such as a desk moving under a zone, or the timezone moving to an address, every caller that walks the path breaks. They break even though they never cared about the path, only the answer at the end. The usual fix is not to ban dots. You move the question closer to the object that can answer it, or let an intermediate object answer on behalf of its neighbours.

Signs

How to spot it in a review.

  • The same long prefix, such as booking.getDesk().getFloor().getBuilding(), appears several times in one function or across modules.
  • A caller imports or mentions types it never otherwise uses, only because they sit in the middle of a path.
  • A structural change to one class, like moving a field from Building to Address, causes edits in many unrelated files.
  • Tests need to build a deep graph of objects or mocks returning mocks just to reach one value.
  • Null checks pile up at each hop because any link in the chain might be missing.

What it looks like

A typical case, in three languages.

class Address {
  constructor(private street: string, private city: string) {}
  getStreet(): string { return this.street; }
  getCity(): string { return this.city; }
}

class Building {
  constructor(
    private name: string,
    private timezone: string,
    private badgeRequired: boolean,
    private address: Address,
  ) {}
  getName(): string { return this.name; }
  getTimezone(): string { return this.timezone; }
  requiresBadge(): boolean { return this.badgeRequired; }
  getAddress(): Address { return this.address; }
}

class Floor {
  constructor(private level: number, private building: Building) {}
  getLevel(): number { return this.level; }
  getBuilding(): Building { return this.building; }
}

class Desk {
  constructor(private code: string, private floor: Floor) {}
  getCode(): string { return this.code; }
  getFloor(): Floor { return this.floor; }
}

class Booking {
  constructor(private memberEmail: string, private desk: Desk) {}
  getMemberEmail(): string { return this.memberEmail; }
  getDesk(): Desk { return this.desk; }
}

function buildReminder(booking: Booking): string {
  const city = booking.getDesk().getFloor().getBuilding().getAddress().getCity();
  const level = booking.getDesk().getFloor().getLevel();
  const tz = booking.getDesk().getFloor().getBuilding().getTimezone();
  const badge = booking.getDesk().getFloor().getBuilding().requiresBadge() ? " Bring your badge." : "";
  return `Desk ${booking.getDesk().getCode()}, level ${level}, ${city} (times in ${tz}).${badge}`;
}

const hq = new Building("Harbour House", "Europe/Lisbon", true, new Address("Rua do Cais 12", "Lisbon"));
const booking = new Booking("ines@example.com", new Desk("A-14", new Floor(3, hq)));
console.log(buildReminder(booking));

All three print Desk A-14, level 3, Lisbon (times in Europe/Lisbon). Bring your badge. The reminder code for a coworking app knows the full path from booking to desk to floor to building to address. If the team adds zones between floors and desks, this function breaks. A cleaner shape: give Building a locationSummary() that returns the city, timezone and badge text. Give Floor a describe() that adds the level. Desk then delegates to Floor, so buildReminder only calls booking.getDesk().describe() or, with one more hidden delegate, booking.describeLocation().

Why it happens

How code ends up like this.

  • Every hop in the chain is a dependency, so the caller is coupled to the shape of the whole object graph rather than to the one object it talks to.
  • Restructuring the model, such as inserting, removing or reordering a link, forces edits in every caller that walks the path.
  • The logic that belongs to the end of the chain ends up spread among callers, so the same formatting or decision gets duplicated.
  • Testing the caller needs a deep fixture or a mock that returns a mock that returns a mock, which makes tests brittle and hard to read.

Treatment

The refactorings that cure it, and when to choose each.

Payoff

What you get once it's gone.

  • Callers depend only on their immediate collaborator, so changes to the deeper structure stay local.
  • Logic about locations, prices or permissions lives with the data it uses instead of being copied into callers.
  • Tests can build one object or stub one method instead of assembling a deep graph.
  • Call sites read as intent, like booking.describeLocation(), rather than as directions through the model.

When to leave it

Sometimes it's not worth fixing.

  • Fluent APIs and builders that return the same object or the same kind of object, such as query builders or list.filter().map().sort(), are not message chains. You are not navigating a structure.
  • Plain data transfer objects or parsed config that exist only to be read, where the shape is the contract, can be traversed directly. Wrapping every path would just add noise.
  • A single short hop inside one module, such as order.customer.name in a view template, is usually fine until it starts repeating or the structure starts changing.

Common questions

Short answers to the usual doubts.

Is this the same as the Law of Demeter?

They are closely related. The Law of Demeter says a method should talk only to its own fields, its parameters, objects it creates and itself. A message chain is the most visible way to break that rule. Treat the law as a guideline that points at coupling, not as a dot-counting rule. Chaining calls on a stream or a builder technically adds dots but doesn't couple you to anyone's internal structure.

Doesn't hiding every delegate turn my classes into middle men?

It can. If Booking ends up with fifteen methods that each forward to Desk, Floor or Building, you have traded one smell for another. Hide delegates that many callers need, and move real behaviour to where the data lives instead of only forwarding. If a class becomes mostly forwarding, use remove-middle-man and accept a short, stable chain.

How do I decide where the extracted method should live?

Look at which object's data the method reads most. In the reminder example, city, timezone and badge policy all belong to Building, so a location summary belongs there. The level belongs to Floor, so Floor adds it. Each object answers about itself, and the caller asks only the first one.

How should I talk about message chains in an interview?

Explain the cost in terms of change, not style. For example: this function knows four classes deep, so adding a zone between floor and desk would break it. Then name the fix and the trade-off. Hide the delegate or move the behaviour, but watch for creating a middle man. Interviewers usually want to see that you know dots are not the problem in themselves. Coupling to structure is.

Next guide4 of 5 · Smells: couplingMiddle ManRead the next one