LLD

Design Principles

Law of Demeter

A method should talk to the objects it holds or is handed, not to objects it digs out of them. We build a hotel checkout twice, once reaching through a chain of getters and once asking one object for the answer, and see what moving the minibar costs each time.

At checkout in a hotel in Udaipur, the front desk tells the guest the bill and asks how they want to pay. The clerk does not open the guest's bag to find their wallet.

The Law of Demeter says the same about code: a method should talk to its friends, not to strangers.

The principle

A method's friends are:

  • its own object,
  • the object's fields,
  • its parameters,
  • objects the method creates.

A method may call methods on any of these. The elements of a list the object holds count as friends too. An object that a friend hands back from inside itself is a stranger. If guest is a parameter, guest.getBooking() is fine. Calling getRoom() on the booking it returns is talking to a stranger. The method now depends on how a guest holds a booking and how a booking holds a room.

The fix is usually "tell, don't ask". The method stops asking for parts and doing the sum itself. It tells a friend to do the job, or asks it for the finished answer.

What it does not say

It is not "count the dots". This chain has four:

long revenue = bookings.stream()        .filter(Booking::isCheckedOut)        .mapToLong(Booking::total)        .sum();

Each call returns a new stream made for the caller, and the last one returns a number. None of them is a part of another object. The bookings are elements of a list the method holds, and the code never reaches into a booking's parts. A builder, where each call returns the builder, is the same. The test is whether a call hands back an object from inside another object.

Example: a hotel checkout

CheckoutDesk works out the bill and takes it from the guest's prepaid wallet. Money is whole dollars in a long:

final class CheckoutDesk {    long checkout(Guest guest) {        int nights = guest.getBooking().getNights();        long rate = guest.getBooking().getRoom().getNightlyRate();        long minibarCharges = guest.getBooking().getRoom().getMinibar().getCharges();        long total = Math.addExact(Math.multiplyExact(nights, rate), minibarCharges);        guest.getWallet().debit(total);        return total;    }}

guest is a parameter, so it is a friend. The booking, the room, the minibar and the wallet are strangers. CheckoutDesk depends on five classes and on how each one holds the next. Moving the chains into local variables would remove the dots but not these dependencies.

The desk reaches through the guest
CheckoutDesk is handed a Guest and then calls four objects it was never given. A purple tag marks Guest as the only friend, and red tags mark Booking, Room, Minibar and Wallet as strangers. Each arrow from the desk is a call, and each red one goes past the guest into its parts.CheckoutDesk is handed a Guest and then calls four objects it was never given. A purple tag marks Guest as the only friend, and red tags mark Booking, Room, Minibar and Wallet as strangers. Each arrow from the desk is a call, and each red one goes past the guest into its parts.
CheckoutDesk has one friend and calls four strangers. CheckoutDesk is handed a Guest and then calls four objects it was never given. A purple tag marks Guest as the only friend, and red tags mark Booking, Room, Minibar and Wallet as strangers. Each arrow from the desk is a call, and each red one goes past the guest into its parts.

Two more classes reach the minibar the same way. NightAuditReport lists every room's charges at midnight, and RunningBillScreen shows a guest the bill so far in the hotel app.

The change request

The hotel fits smart minibars that keep their own tally. The charges now come from a MinibarService, looked up by room number, and Room no longer holds a Minibar. getMinibar() is gone, so all three callers stop compiling. Each one is edited to take a MinibarService in its constructor and to look up the room number itself. Three classes change for a decision that belongs to the room.

One move, three edits
Each of the three callers holds a copy of the chain down to Minibar, so moving the minibar edits all three. Amber outlines mark the edited callers. A red outline marks Minibar, which is removed from Room, and the grey MinibarService is the new place the charges come from. Each caller now depends on that service as well.Each of the three callers holds a copy of the chain down to Minibar, so moving the minibar edits all three. Amber outlines mark the edited callers. A red outline marks Minibar, which is removed from Room, and the grey MinibarService is the new place the charges come from. Each caller now depends on that service as well.
Every caller with the chain is edited when the minibar moves. Each of the three callers holds a copy of the chain down to Minibar, so moving the minibar edits all three. Amber outlines mark the edited callers. A red outline marks Minibar, which is removed from Room, and the grey MinibarService is the new place the charges come from. Each caller now depends on that service as well.

Following the principle

We give each object a method for the question its callers have. Room answers its minibar charges, and Booking answers its total:

final class Booking {    private final Room room;    private final int nights;     long extras() {        return room.minibarCharges();    }     long total() {        long roomCharges = Math.multiplyExact(nights, room.nightlyRate());        return Math.addExact(roomCharges, extras());    }}

Guest gets bill(), which returns booking.total(), and pay(amount), which debits its wallet. The desk now talks only to its parameter:

long checkout(Guest guest) {    long bill = guest.bill();    guest.pay(bill);    return bill;}

The night audit calls booking.extras(), and the running bill calls guest.bill().

Now the same change request arrives. Room swaps its Minibar field for a MinibarService and passes its own number to it:

final class Room {    private final String number;    private final long nightlyRate;    private final MinibarService minibarService;     long minibarCharges() {        return minibarService.chargesFor(number);    }}

Only Room and the code that builds rooms are edited. The three callers are not opened.

The same move, after
With tell, don't ask, the minibar move edits only Room. Each caller talks only to the one object it is given. Booking asks Room, and Room is the one class that knows where minibar charges come from. The amber outline marks Room, the only edit. The grey MinibarService is outside our code.With tell, don't ask, the minibar move edits only Room. Each caller talks only to the one object it is given. Booking asks Room, and Room is the one class that knows where minibar charges come from. The amber outline marks Room, the only edit. The grey MinibarService is outside our code.
Each caller asks its friend, so the move edits only Room. With tell, don't ask, the minibar move edits only Room. Each caller talks only to the one object it is given. Booking asks Room, and Room is the one class that knows where minibar charges come from. The amber outline marks Room, the only edit. The grey MinibarService is outside our code.

The opposite mistake

A wrapper that only forwards getters removes the chain but leaves the work in the caller. Here Guest passes each part through, and Booking does the same for Room:

final class Guest {    private final Booking booking;     int getNights() {        return booking.getNights();    }     long getNightlyRate() {        return booking.getNightlyRate();    }     long getMinibarCharges() {        return booking.getMinibarCharges();    }}

This version survives the minibar move, because only Room knows where the charges come from. But the desk and the running bill still multiply and add the parts themselves. If the hotel must add Goods and Services Tax (GST) to the bill, both callers change. In the tell, don't ask version, only Booking.total() changes. The wrappers also gain a method whenever a caller wants another part. A good method answers the caller's question, like bill(), or does a job, like pay.

When not to

Values are the usual exception. booking.checkInDate().getDayOfWeek() asks a LocalDate, which never changes and will not move behind a service. A record or a data transfer object exists to carry data, so reading its parts is its job. A test or a one-off report that reads a nested value once does not need a new method on three classes.

In an interview

When we write a.getB().getC().doSomething(), we stop and ask which object should answer, and give it a method. Then we name the change this protects against: "if the minibar moves, only Room changes." The Encapsulation page does the same with a wallet: callers tell it to debit, and it applies its own rules. The Facade pattern page uses the idea at a larger scale, with one object in front of five subsystems.

Common mistakes:

  • Counting dots. Stream and builder chains are fine. A chain of getters through another object's parts is not.
  • Hiding the chain in local variables. Fewer dots on a line do not remove the dependency on each class.
  • Forwarding every getter. The chain moves into the wrapper, and the caller still does the work.

Summary

  • A method talks to its friends: its own object, its fields, its parameters and objects it creates.
  • A chain of getters ties the caller to how every object along it is built, so one move edits every caller.
  • Tell, don't ask: the object that holds the data gets a method that answers the question or does the job.
  • Dots are not the test. Streams, builders and values are fine, and wrappers that only forward getters are not a fix.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.