Lesson 8 of 45 · Principles of Good Object Design
The Law of Demeter
The chain you've definitely written
Somewhere in a codebase you've worked on, there's a line like $reservation->getGuest()->getBillingAddress()->getCountry()->getCode(), or $invoice->getReservation()->getRatePlan()->getPolicy()->isRefundable().
Each step looks fine on its own. Each ->get*() returns a real object. The IDE autocompletes happily through the whole chain. The line works.
It also breaks if any of the four classes it walks through changes shape.
Rename getCountry() to country(), and the chain breaks. Make getBillingAddress() nullable, and the chain throws. Refactor RatePlan to not own the policy directly anymore, and every chain that walked through it has to be rewritten. The line knows too much about how four other classes are arranged internally, and every change to any of them ripples here.
This is what the Law of Demeter is trying to prevent.
What the Law of Demeter actually says
The Law of Demeter (LoD) is a coupling rule. Ian Holland formulated it at Northeastern University in the fall of 1987, during the Demeter project, and the project's own page puts the general version like this:
Each unit should only talk to its friends; Don't talk to strangers.
The version most developers learn is a simplification of the project's object-oriented form:
A method should only call methods on:
Itself
Its own properties
Objects passed to it as arguments
Objects it creates locally
Anything else is a "stranger", and reaching out to talk to one is the smell.
A quick smell detector is to count the calls in a single expression. Three or more calls, each returning an object you keep navigating, is the smell. $guest->getName() is fine. $reservation->getGuest()->getBillingAddress()->getCountry()->getCode() is a problem.
The count is not the rule itself, and some chains are perfectly fine (we'll come back to that). The rule catches something more specific: when you reach through one object to talk to another object, the calling code becomes coupled to the structure of the first object.
A worked example
Here's a chain like the ones in the opening, refactored toward LoD. PaymentRouting decides whether an invoice's payment goes through the EU payment processor (the classes below are trimmed to what this lesson needs, and the EU code list is cut to three countries):
Before:
<?php
declare(strict_types=1);
namespace App\Payments;
use App\Billing\Invoice;
final class PaymentRouting
{
private const EU_COUNTRIES = ['DE', 'FR', 'ES'];
public function usesEuProcessor(Invoice $invoice): bool
{
$countryCode = $invoice->getReservation()->getGuest()->getBillingAddress()->getCountry()->getCode();
return in_array($countryCode, self::EU_COUNTRIES, true);
}
}After:
<?php
declare(strict_types=1);
namespace App\Payments;
use App\Billing\Invoice;
final class PaymentRouting
{
public function usesEuProcessor(Invoice $invoice): bool
{
return $invoice->isBilledInEu();
}
}With each class along the way owning the question at its own level:
<?php
declare(strict_types=1);
namespace App\Billing;
use App\Reservations\Reservation;
final class Invoice
{
public function __construct(private Reservation $reservation) {}
public function isBilledInEu(): bool
{
return $this->reservation->isBilledInEu();
}
}<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Booking\Guest;
final class Reservation
{
public function __construct(private Guest $guest) {}
public function isBilledInEu(): bool
{
return $this->guest->isBilledInEu();
}
}<?php
declare(strict_types=1);
namespace App\Booking;
final class Guest
{
public function __construct(private BillingAddress $billingAddress) {}
public function isBilledInEu(): bool
{
return $this->billingAddress->isInEu();
}
}<?php
declare(strict_types=1);
namespace App\Booking;
final class BillingAddress
{
public function __construct(private Country $country) {}
public function isInEu(): bool
{
return $this->country->isInEu();
}
}<?php
declare(strict_types=1);
namespace App\Booking;
final class Country
{
private const EU_CODES = ['DE', 'FR', 'ES'];
public function __construct(private string $code) {}
public function isInEu(): bool
{
return in_array($this->code, self::EU_CODES, true);
}
}The original line knew about Invoice, Reservation, Guest, BillingAddress, Country, and the concept of EU codes. The refactored version knows about Invoice and the question "is this billed in the EU?". The knowledge of how that question gets answered lives in the chain of objects, each of which knows only its own immediate friend.
That's what LoD buys you. The original was one line; the refactored version is a method on each of five classes. It is more code, and when one class changes its internal layout, only that class's method changes.
You don't need a delegating method on every class along the way. The goal is to collapse the question into one place at the top, then let each class answer it using only its direct collaborators. If Reservation and Guest are closely tied together, Reservation::isBilledInEu() can read the guest's billing address itself. The judgement call is where the genuine boundaries are.
Why long chains hurt
Three concrete costs to chains that reach past their immediate friends:
Coupling to structure. The chain knows that
Reservationhas aGuest, thatGuesthas aBillingAddress, thatBillingAddresshas aCountry. That's a lot of facts to be true. If any of them changes (the guest's address moves to a separateProfileobject, the country becomes a property of the address rather than its own object), the chain breaks.Brittleness across files. A change to a class somewhere "low" in the chain (like adding a nullable return type to
getBillingAddress) shows up as a bug in code that doesn't import the class directly. The cost-of-change curve climbs faster, because the impact radius of every change is larger than the file it lives in.Exposing internal arrangement. A class that returns its internal collaborators, that return their internal collaborators, that return their internal collaborators, encapsulates nothing: it is a database with method-call syntax. The "private" properties may as well be public, because anyone who can call
getGuest()can pretend the guest is a public field.
The deeper problem is the same as Tell, Don't Ask from the previous lesson, applied to navigation rather than decision-making. The chain asks one object after another for its parts, where one question to the right object would do.
"Train wreck" code
Robert C. Martin's Clean Code calls these chains train wrecks. The -> calls line up like train cars; if any car derails, everything behind it derails too.
For example, $session->getGuest()->getProfile()->getPreferences()->getNotifications()->getEmail()->isEnabled().
You can usually spot a train wreck by:
Three or more
->calls in a single expression (with each one returning an object you keep navigating).Each step is a "get" or accessor.
The thing at the end of the chain is a primitive value (a string, a bool, an int) that the original caller wants to ask a question about.
When you see one, ask what question the code is trying to answer. The answer is almost always a single sentence ("is the guest opted in to email notifications?"), and that sentence is the method you want.
Where chains are fine
To stay honest with the "tools, not rules" framing, not every chain is a violation. A few cases where chains are fine and shouldn't be refactored:
Fluent interfaces by design. Query builders, HTTP client builders, validation builders.
User::query()->where('email', $email)->orderBy('created_at')->first()is one chain, but each step untilfirst()returns the same builder object, designed for chaining. The Law of Demeter is about coupling to other objects' structures; fluent interfaces are coupling to one object's deliberate API.Value objects you're just reading.
$money->currency->isoCodeis technically a two-link chain. IfMoneyandCurrencyare stable value objects with clear APIs, the chain is just reading data through a shape that exists by design. Refactoring it into$money->currencyCode()is fine, but not refactoring it isn't a sin.Inside the same module. Within a tightly cohesive module that genuinely owns a graph of related concepts, a small amount of chaining can be cheaper than wrapping every traversal in a delegation method. The cost-benefit changes when the chain crosses module boundaries.
Chains the business thinks in.
$invoice->reservation->guestcan be fine when that is how the business talks about it. The smell is reaching further than the business model justifies.Very short chains over genuinely owned data.
$this->reservation->total()is fine;$thisis a "self" friend, andreservationis a property. The rule allows a single hop into a friend's API.
The smell is sharper when the chain crosses object boundaries that have no business being bound together ($invoice->getReservation()->getGuest()->getRatePlan()). It's softer when the chain stays within a deliberately exposed API.
Pitfalls
Delegation explosion. Following the rule mechanically can produce dozens of one-line methods, each of which forwards to the next object's one-line method. That's the over-engineering trap. The fix is to think about what question the calling code is actually asking, and put a method with that name on the right object. Invoice::isBilledInEu() is a real concept; Invoice::getReservationGuestBillingAddressCountry() is just the chain in method form.
Wrapping primitives unnecessarily. "Tell, don't ask" plus LoD can lead someone to wrap every primitive in a method. $guest->getId() becoming $guest->doSomethingWithId(...) for every operation just to avoid asking. That's overkill. Reading a value to use it (display it, compare it, log it) is fine. The rule fires when you're reading values to navigate further into other objects.
Treating Eloquent relationships as the rule's enemy. $guest->reservations()->where('status', 'confirmed')->get() is fine. The relationship method on the model returns a query builder; the chain is the framework's deliberate API. Refusing to write Eloquent code because it chains calls is fighting the framework rather than improving the code.
A practical move
When you spot a train wreck in a code review, the move is:
Read the chain out loud as a sentence. "Get the invoice's reservation's guest's billing address's country's code, and check if it's in the EU."
Find the noun the question is really about (here, the invoice) and phrase the question about it: "Is this invoice billed in the EU?"
Add that method to the class the question is most naturally asked of (
Invoice::isBilledInEu()).Let the implementation push the question down the chain, one short delegation at a time, until each method only asks its immediate friend.
Refactors of this kind are mechanical once you've identified the question. The skill is in spotting when you have a question hiding inside a navigation chain, not in writing the delegation methods themselves.
The one thing to remember
If you find yourself navigating through three or more objects in a single expression to ask a question, the chain is telling you the question wants to be a method on the first object in the chain.
Related Links
- Law of Demeter (General Formulation)The Demeter Project's page on the general formulation of the law, including when and by whom it was first proposed at Northeastern University.
- Law of Demeter: Principle of Least KnowledgeKarl Lieberherr's own page on the law, with a link to his and Ian Holland's 1989 IEEE Software paper on it.
- Hide DelegateFowler's refactoring catalog entry for the fix this lesson recommends, wrapping a delegation chain in a method instead of exposing it.