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));from dataclasses import dataclass
@dataclass
class Address:
street: str
city: str
@dataclass
class Building:
name: str
timezone: str
requires_badge: bool
address: Address
@dataclass
class Floor:
level: int
building: Building
@dataclass
class Desk:
code: str
floor: Floor
@dataclass
class Booking:
member_email: str
desk: Desk
def build_reminder(booking: Booking) -> str:
city = booking.desk.floor.building.address.city
level = booking.desk.floor.level
tz = booking.desk.floor.building.timezone
badge = " Bring your badge." if booking.desk.floor.building.requires_badge else ""
return f"Desk {booking.desk.code}, level {level}, {city} (times in {tz}).{badge}"
hq = Building("Harbour House", "Europe/Lisbon", True, Address("Rua do Cais 12", "Lisbon"))
booking = Booking("ines@example.com", Desk("A-14", Floor(3, hq)))
print(build_reminder(booking))<?php
final class Address
{
public function __construct(private string $street, private string $city) {}
public function getStreet(): string { return $this->street; }
public function getCity(): string { return $this->city; }
}
final class Building
{
public function __construct(
private string $name,
private string $timezone,
private bool $badgeRequired,
private Address $address,
) {}
public function getName(): string { return $this->name; }
public function getTimezone(): string { return $this->timezone; }
public function requiresBadge(): bool { return $this->badgeRequired; }
public function getAddress(): Address { return $this->address; }
}
final class Floor
{
public function __construct(private int $level, private Building $building) {}
public function getLevel(): int { return $this->level; }
public function getBuilding(): Building { return $this->building; }
}
final class Desk
{
public function __construct(private string $code, private Floor $floor) {}
public function getCode(): string { return $this->code; }
public function getFloor(): Floor { return $this->floor; }
}
final class Booking
{
public function __construct(private string $memberEmail, private Desk $desk) {}
public function getMemberEmail(): string { return $this->memberEmail; }
public function getDesk(): Desk { return $this->desk; }
}
function buildReminder(Booking $booking): string
{
$city = $booking->getDesk()->getFloor()->getBuilding()->getAddress()->getCity();
$level = $booking->getDesk()->getFloor()->getLevel();
$tz = $booking->getDesk()->getFloor()->getBuilding()->getTimezone();
$badge = $booking->getDesk()->getFloor()->getBuilding()->requiresBadge() ? ' Bring your badge.' : '';
return sprintf('Desk %s, level %d, %s (times in %s).%s', $booking->getDesk()->getCode(), $level, $city, $tz, $badge);
}
$hq = new Building('Harbour House', 'Europe/Lisbon', true, new Address('Rua do Cais 12', 'Lisbon'));
$booking = new Booking('ines@example.com', new Desk('A-14', new Floor(3, $hq)));
echo buildReminder($booking), PHP_EOL;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.
- Hide Delegate: Stop Callers Reaching Through an Object's Internals
A caller asks an object for its neighbour only to ask that neighbour for something. Add a method on the first object, such as
Booking.timezone(), that does the forwarding. - Extract function: give a fragment a name
The code that uses the end of the chain does real work. Pull that block into its own function first so you can see exactly what the caller needs.
- Move Function: Put Behaviour Next to the Data It Uses
After extracting, the new function mostly talks to the object at the end of the chain. Move it there, or to the nearest object that can answer the question.
- Extract Variable: Give a Complex Expression a Name
As a quick first step when the same prefix repeats: store
booking.getDesk().getFloor().getBuilding()once. This doesn't remove the coupling but it makes the remaining dependency obvious. - Remove Middle Man: Let Callers Talk to the Real Object
Hiding delegates has gone too far and a class is now mostly one-line forwarding methods. Let callers reach the delegate directly again.
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.namein 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.