The Law of Demeter
What you will learn on this page
Section titled “What you will learn on this page”- What the Law of Demeter says, in one sentence and as a short list of “who may I call?” rules.
- How to recognise a train-wreck call such as
order.customer().membership().add_points(20), and why the problem is the knowledge it needs, not the number of dots. - How tell, don’t ask fixes it: move the decision to the object that owns the data.
- Why adding a forwarding function for every part is not a fix, and how to forward by intent instead.
- When the law does not apply: plain values, fluent builders, range pipelines, and data structures that are meant to be walked.
The problem
Section titled “The problem”A web shop’s dispatch desk prints a label for each order and sends the parcel. The requirements:
- FR-1 Each label is addressed to where the order must be delivered.
- FR-2 Parcels for premium members are marked PRIORITY.
- FR-3 Shipping an order earns the buyer loyalty points: 10, or 20 for premium members. An order earns points once.
- FR-4 (added this year by the order team) An order can be a gift, delivered to someone else’s address. The buyer still earns the points.
After FR-4 was released, gifts kept arriving at the buyer’s home, and a customer whose label printer jammed got their points twice. Nobody had changed the dispatch code.
The law in one sentence
Section titled “The law in one sentence”The Law of Demeter, also called the principle of least knowledge, says: a function should talk only to its immediate friends, not to the friends of its friends.
More precisely, inside a member function f of class X, it is fine to
call functions on the objects below. (The examples imagine a Dispatcher
class with a printer, and a Label with a validate function; the
example code uses a free dispatch function to stay small.)
| Who | Example inside Dispatcher::dispatch(Order& order) |
|---|---|
X itself (this) |
log_dispatch(...) |
f’s parameters |
order.mark_shipped() |
objects f creates |
Label label{...}; label.validate(); |
X’s own data members |
printer_.print(label) |
| (globals and free functions in scope; a common practical addition to the original list) | std::format(...) |
What is not on the list: objects that one of those returned. If
order.customer() hands back a Customer&, calling
order.customer().membership() is talking to a stranger, and
order.customer().membership().add_points(20) is talking to the stranger’s
friend.
Count the knowledge, not the dots
Section titled “Count the knowledge, not the dots”A chain such as order.customer().membership().add_points(20) is often
called a train wreck: one call coupled to the next like railway cars.
But the dots are only a symptom. The real question is: how much does
this line know about objects it does not own?
That one line knows that:
- an order has a customer (and only one);
- a customer has a membership object;
- the membership is where points are kept, and it may be changed from outside;
- the points rule is “add a number”, not “record an order”.
If any of those facts changes, this line breaks, even though its own job (dispatching parcels) did not change. That is coupling to the structure of three other classes.
Splitting the chain into named variables does not help:
// The same chain as order.customer().membership().add_points(20), one// step per line. Each `&` variable is a reference: another name for the// object inside the order and the customer, not a copy of it.Customer& customer = order.customer();Membership& membership = customer.membership();membership.add_points(20); // changes the real membership, through two hopsIt has fewer dots per line, but it knows exactly the same things. Likewise, a long chain can be harmless, as the section on when the law does not apply shows.
The design, step by step
Section titled “The design, step by step”Text description of the diagram
The dispatcher asks the order for its customer and gets a reference to the
customer back. It asks the customer for their home address, then for their
membership, and gets a reference to the membership back. It asks the
membership whether it is premium, then tells it to add 10 or 20 points.
Finally it tells the order it is shipped. The dispatcher sends messages to
three objects, and two of them (the customer and the membership) it only
reached through the order. The real code calls customer() three times
and membership() and is_premium() twice; the diagram shows each once.
Diagram source (Mermaid)
sequenceDiagram
participant Desk as dispatch()
participant Ord as Order
participant Cust as Customer
participant Mem as Membership
Desk->>Ord: customer()
Ord-->>Desk: Customer&
Desk->>Cust: home()
Cust-->>Desk: const Address&
Desk->>Cust: membership()
Cust-->>Desk: Membership&
Desk->>Mem: is_premium()
Mem-->>Desk: bool
Desk->>Mem: add_points(10 or 20)
Desk->>Ord: mark_shipped()This is tell, don’t ask:
instead of pulling data out of an object and deciding for it, the caller
tells the object what happened and lets it apply its own rules. Questions
are still allowed (delivery_address() and priority() are questions),
but each is a question about the order itself, answered by the order.
The new design
Section titled “The new design”struct Address
a plain value
Data members
std::string name;std::string street;std::string postcode;std::string country;
struct Label
a plain value, what the printer needs
Data members
std::string to;std::string street;std::string postcode;std::string country;bool priority = false;
class Membership
owns the points and the points rule
Data members
bool premium_;int points_ = 0;
Member functions
bool is_premium() const;int points() const;void award_for_order();10, or 20 for premium
class Customer
owns their home and their membership
Data members
Address home_;Membership membership_;
Member functions
const Address& home() const;bool is_premium() const;int points() const;void record_shipped_order();tells the membership
class Order
knows its customer, the gift address, and whether it has shipped
Data members
int number_;Customer& customer_;not owned; the customer list outlives ordersstd::optional<Address> gift_address_;bool shipped_ = false;
Member functions
int number() const;void ship_to(Address address);throws once shippedconst Address& delivery_address() const;gift address, or the customer's homebool priority() const;bool shipped() const;void mark_shipped();throws if already shipped
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// After: each class answers questions about itself and does the work its// own data is needed for. Nobody hands out a part to be changed.// Owns the points rule now. There is no add_points: the only way to gain// points is award_for_order, so no caller can invent its own amount.class Membership {public: explicit Membership(bool premium) : premium_{premium} {} [[nodiscard]] bool is_premium() const { return premium_; } [[nodiscard]] int points() const { return points_; } void award_for_order(); // the points rule: 10, or 20 for premium members
private: bool premium_; int points_ = 0;};
// The customer answers for its membership instead of handing it out. The// three one-line functions forward to membership_, so callers never learn// that a Membership object exists.class Customer {public: Customer(Address home, Membership membership); [[nodiscard]] const Address& home() const { return home_; } [[nodiscard]] bool is_premium() const { return membership_.is_premium(); } [[nodiscard]] int points() const { return membership_.points(); } void record_shipped_order() { membership_.award_for_order(); }
private: Address home_; Membership membership_;};
// The order answers the questions the dispatcher has (where to? priority?)// and does the shipping work itself. It no longer hands out its customer.class Order {public: // Keeps a reference to `customer`: the Customer must outlive the Order. Order(int number, Customer& customer) : number_{number}, customer_{customer} {}
// A gift: deliver to someone else. Throws std::logic_error once shipped. void ship_to(Address address);
[[nodiscard]] int number() const { return number_; } [[nodiscard]] const Address& delivery_address() const; // the gift address, or the customer's home [[nodiscard]] bool priority() const { return customer_.is_premium(); } [[nodiscard]] bool shipped() const { return shipped_; }
// Throws std::logic_error if already shipped, so points are awarded once. void mark_shipped();
private: int number_; Customer& customer_; // not owned; the customer list outlives orders std::optional<Address> gift_address_; // empty unless ship_to was called bool shipped_ = false;};
// Talks only to the order it is given, and reads the Address value it gets back.[[nodiscard]] Label dispatch(Order& order);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The points rule, in one place: 20 points for a premium member, else 10.void Membership::award_for_order() { points_ += premium_ ? 20 : 10; }
// `home` is moved into home_ (its strings are taken over, not copied// again); the small Membership is copied.Customer::Customer(Address home, Membership membership) : home_{std::move(home)}, membership_{membership} {}
// A gift address can be set or changed only before the order ships. The// check comes first, so a refused call changes nothing.void Order::ship_to(Address address) { if (shipped_) throw std::logic_error("order already shipped"); gift_address_ = std::move(address);}
// "If there is a gift address, that one; otherwise the customer's home."// An optional converts to true when it holds a value, and *gift_address_// is the Address inside it. Both choices are existing objects, so this// returns a reference to one of them, not a copy.const Address& Order::delivery_address() const { return gift_address_ ? *gift_address_ : customer_.home();}
// The "once" rule lives here: a second call throws before anything// changes, so the points cannot be awarded twice. The order tells its// customer, and the customer tells its membership: each object talks only// to the one it holds.void Order::mark_shipped() { if (shipped_) throw std::logic_error("order already shipped"); shipped_ = true; customer_.record_shipped_order();}
// Talks only to `order`. Shipping comes first, so a repeated dispatch// throws before any label is made. `to` refers to the gift address or the// customer's home, both of which outlive this function. The braces build// the returned Label field by field, copying the address strings into it.Label dispatch(Order& order) { order.mark_shipped(); // throws before a second label is made const Address& to = order.delivery_address(); return {to.name, to.street, to.postcode, to.country, order.priority()};}How this code works: dispatch and Order::mark_shipped
dispatchships first. It callsorder.mark_shipped()before it reads anything. If the order has already shipped,mark_shippedthrowsstd::logic_erroranddispatchstops there: no label, no points.mark_shippedpasses the news down one step at a time. It setsshipped_totrue, then callscustomer_.record_shipped_order(). The customer callsmembership_.award_for_order(), which adds 20 points for a premium member and 10 otherwise. The dispatcher never sees the customer or the membership.dispatchasks where to go.delivery_address()returns a reference to the gift address ifship_toset one, otherwise to the customer’s home. Nothing is copied yet.dispatchbuilds the label. Thereturn { ... }line copies the four strings from that address into a newLabeland addsorder.priority(), which is the customer’s premium flag.
A trace with the example program’s orders (Ana is premium; Ben is not; Ben’s order is a gift for Cy):
| Call | shipped_ before |
Points awarded | Label goes to |
|---|---|---|---|
dispatch(first) (Ana) |
false |
Ana +20 | Ana Silva |
dispatch(gift) (Ben) |
false |
Ben +10 | Cy Rossi |
dispatch(first) again |
true |
none: throws | no label |
The third row is the “jammed printer”. The example program does not make
that call; the test points_are_awarded_once does.
Text description of the diagram
The dispatch function tells the order it has shipped. The order, which refuses if it has already shipped, tells its customer to record a shipped order, and the customer tells its membership to award the points for an order. Then the dispatch function asks the order for its delivery address, and the order returns the gift address if there is one, otherwise the customer’s home. Last, it asks the order whether it is priority and gets a true or false answer. Each object sends messages only to objects it holds directly.
Diagram source (Mermaid)
sequenceDiagram
participant Desk as dispatch()
participant Ord as Order
participant Cust as Customer
participant Mem as Membership
Desk->>Ord: mark_shipped()
Ord->>Cust: record_shipped_order()
Cust->>Mem: award_for_order()
Desk->>Ord: delivery_address()
Ord-->>Desk: const Address& (gift, or home)
Desk->>Ord: priority()
Ord-->>Desk: boolCompare the two sequence diagrams. Before, the dispatcher had arrows to three objects. After, it has arrows to one, and each object passes the message one step to an object it holds. The work did not disappear; it moved next to the data it needs.
Why each choice
Section titled “Why each choice”| Choice | Why |
|---|---|
delivery_address() lives in Order |
Order owns the gift address, so it is the only class that can answer correctly. When the order team added gifts, the answer would have changed in the same class as the data. |
priority() is a question about the order |
The name says what the dispatcher needs (how to handle this parcel), not where the answer comes from. If priority later also depends on an express option, only Order::priority changes. |
mark_shipped() is a command that passes the event on |
“Points once per order” is a rule about the order, so the order enforces it, by refusing a second call. A getter cannot protect a rule; a command can. |
Customer::record_shipped_order(), not membership() |
Customer no longer hands out a Membership& for others to change. Points can only change through the one function that applies the rule, so the “10 or 20” rule has one home (see DRY). |
Customer keeps is_premium() and points() queries |
These two do forward to Membership, but deliberately: they are read-only questions that the order and the account page need, and they cannot break a rule. If the list keeps growing, they should become intent-named functions too. |
Order holds a Customer& |
The order does not own its customer: the customer list owns customers and outlives every order. A reference says “never null, not owned”. It also makes Order non-assignable, which this design does not need. |
dispatch calls mark_shipped() first |
If the order has already shipped, it throws before a second label is made. Reading the address afterwards is safe: marking shipped does not change it, and ship_to refuses once shipped. |
delivery_address() returns const Address& |
It refers either to the order’s own gift address or to the customer’s home. It is valid while the order and the customer exist and the gift address is not changed; a caller that keeps it longer must copy it. |
Is this just moving the problem?
Section titled “Is this just moving the problem?”Order::delivery_address calls customer_.home(), and
Customer::record_shipped_order calls membership_.award_for_order().
Both are calls on an object’s own data members, which the law allows.
Each class now knows only about the class it holds directly. If
Membership changes how points are stored, only Customer and
Membership can be affected, and usually only Membership.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Ana is a premium member; Ben is not. Ben's order is a gift for Cy.const Address ana_home{"Ana Silva", "1 Rua Nova", "1100-001", "PT"};const Address ben_home{"Ben Okafor", "9 Mill Lane", "D02 X285", "IE"};const Address gift_for_cy{"Cy Rossi", "4 Via Roma", "00184", "IT"};
std::cout << "-- before --\n";// Each design runs inside its own { } block, so its objects are// destroyed at the closing brace. The customers are declared before the// orders that refer to them, so they live at least as long.{ before::Customer ana{ana_home, before::Membership{true}}; before::Customer ben{ben_home, before::Membership{false}}; before::Order first{1, ana}; before::Order gift{2, ben}; gift.ship_to(gift_for_cy); // copies the address into the order // to_text turns a Label into one line, with "PRIORITY " in front for // a priority parcel. std::cout << "order 1: " << to_text(before::dispatch(first)) << '\n'; std::cout << "order 2: " << to_text(before::dispatch(gift)) << '\n'; std::cout << "points: Ana " << ana.membership().points() << ", Ben " << ben.membership().points() << '\n';}
std::cout << "-- after --\n";{ Customer ana{ana_home, Membership{true}}; Customer ben{ben_home, Membership{false}}; Order first{1, ana}; Order gift{2, ben}; gift.ship_to(gift_for_cy); std::cout << "order 1: " << to_text(dispatch(first)) << '\n'; std::cout << "order 2: " << to_text(dispatch(gift)) << '\n'; std::cout << "points: Ana " << ana.points() << ", Ben " << ben.points() << '\n';}-- before --order 1: PRIORITY Ana Silva, 1 Rua Nova, 1100-001 PTorder 2: Ben Okafor, 9 Mill Lane, D02 X285 IEpoints: Ana 20, Ben 10-- after --order 1: PRIORITY Ana Silva, 1 Rua Nova, 1100-001 PTorder 2: Cy Rossi, 4 Via Roma, 00184 ITpoints: Ana 20, Ben 10For ordinary orders, both designs print the same label and award the same points. For the gift, the old dispatcher prints Ben’s home address; the new one prints Cy’s.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false, and LLD_CHECK_THROWS(expression, type) fails// unless the expression throws that type of exception. They come from the// site's small test header, lld_test.hpp.
// The bug the reaching code had: it never asked the order where to go.LLD_TEST(before_sends_gifts_to_the_buyer) { before::Customer ana{home, before::Membership{false}}; before::Order gift{7, ana}; gift.ship_to(friend_address); LLD_CHECK(before::dispatch(gift).to == "Ana Silva");}
// The fix: the label uses the gift address, and the points still go to// Ana, who placed the order (10, as she is not premium).LLD_TEST(a_gift_goes_to_the_gift_address) { Customer ana{home, Membership{false}}; Order gift{7, ana}; gift.ship_to(friend_address); LLD_CHECK(dispatch(gift).to == "Cy Rossi"); LLD_CHECK(ana.points() == 10); // the buyer still earns the points}
// A premium member's parcel is marked priority and earns 20 points.LLD_TEST(premium_orders_are_priority) { Customer ana{home, Membership{true}}; Order order{1, ana}; const Label label = dispatch(order); LLD_CHECK(label.priority); LLD_CHECK(ana.points() == 20);}
// The rule now lives in one place, so it can protect itself.// The second dispatch (the jammed printer) throws, the points stay at 20,// and a shipped order refuses a new gift address. dispatch is// [[nodiscard]]; `(void)` throws its Label away on purpose without a warning.LLD_TEST(points_are_awarded_once) { Customer ana{home, Membership{true}}; Order order{1, ana}; (void)dispatch(order); LLD_CHECK_THROWS((void)dispatch(order), std::logic_error); LLD_CHECK(ana.points() == 20); LLD_CHECK_THROWS(order.ship_to(friend_address), std::logic_error);}
// The old bug, pinned: two dispatches of one premium order give 20 + 20.LLD_TEST(before_awards_points_every_time) { before::Customer ana{home, before::Membership{true}}; before::Order order{1, ana}; (void)before::dispatch(order); (void)before::dispatch(order); LLD_CHECK(ana.membership().points() == 40);}
// For ordinary orders, both designs print the same label and award the// same points, for premium and ordinary members alike.LLD_TEST(ordinary_orders_are_unchanged) { // The loop runs twice, with premium = true and then premium = false. for (const bool premium : {true, false}) { before::Customer old_ana{home, before::Membership{premium}}; before::Order old_order{1, old_ana}; Customer ana{home, Membership{premium}}; Order order{1, ana}; LLD_CHECK(to_text(before::dispatch(old_order)) == to_text(dispatch(order))); LLD_CHECK(old_ana.membership().points() == ana.points()); }}The tests pin down both old bugs (the gift goes to the buyer, and points
are added on every call), so the claims made above are checked. The
“jammed printer” is simulated simply by calling dispatch twice. The last
test checks that, for ordinary orders of premium and non-premium members,
both designs print the same label and award the same points.
Limits of the example
Section titled “Limits of the example”dispatchis a free function with no printer, to keep the example small. A real dispatcher would hold a printer and a carrier connection, and calling them is fine: they are its own data members.- Points are an
intwith no upper limit, and the customer list that owns the customers is not shown. The example assumes it outlives the orders, as theCustomer&comment says. mark_shippedawards the points before the label is printed. If printing can fail, the design needs a decision about whether a failed print undoes the shipment. (The same is true, less likely, if building theLabelitself throws, for example from running out of memory while copying strings.) the invariants lesson covers how to keep such rules in one place.
When the law does not apply
Section titled “When the law does not apply”The law is about objects with behaviour and hidden state. It is not about every dot in a program.
| Code | Is it a problem? | Why |
|---|---|---|
order.delivery_address().postcode |
no | Address is a plain value with public fields and no rules. Reading its fields is reading data that was handed to you, not reaching into an object. (If Address ever gains rules of its own, it stops being plain data, and this changes.) |
order.lines().front().quantity |
usually no | A read-only view of the order’s own lines, which are values. Fine for reading; if callers start changing lines through it, give Order a command instead. |
label.to.size() |
no | std::string is a value. Its interface is stable and part of the standard library. |
Request::builder().url(page).timeout(seconds).build() |
no | A fluent builder: every call returns the builder itself (or an equivalent builder). You are talking to one object the whole time. |
orders | std::views::filter(is_late) | std::views::transform(to_label) |
no | A range pipeline: each step returns a new view, designed to be combined. No one’s internals are exposed. |
walking a parsed JSON document or a syntax tree: doc["items"][0]["price"] |
usually no | The structure is the interface. Code that reads a tree is supposed to know its shape. Keep that knowledge in one module, though. |
order.customer().membership().add_points(20) |
yes | Changes the state of an object two steps away, and copies a rule that belongs to that object. |
A quick test: if the thing you are chaining through could change its insides without changing the interface you call, and you would break, the chain is a problem. Values, builders, and pipelines do have insides, but they expose a stable interface that is meant to be used this way, so nothing hidden can change under you.
The cost: forwarding functions
Section titled “The cost: forwarding functions”The law has a real cost. Following it without thought adds a function to
Order for every question anyone might ask about a customer, as the
“forwarding getters” version showed. That gives Order a wide interface
that changes whenever Customer does, which is the coupling the law was
meant to remove, moved somewhere else.
The way out is to forward by intent, not by part:
| By part (avoid) | By intent (prefer) |
|---|---|
order.customer_home() |
order.delivery_address() |
order.customer_is_premium() |
order.priority() |
order.customer_add_points(20) |
order.mark_shipped() |
The intent names describe what the caller needs, so they survive
changes to how the answer is found. If you find yourself writing many
by-part forwarders, the caller probably needs a different object: give it
the Customer directly as a parameter instead.
Trade-offs
Section titled “Trade-offs”| You gain | You pay |
|---|---|
| Callers do not break when another class’s insides change | A few more member functions, each with a name to choose |
| Rules (like “points once”) can be enforced, because there is one way in | Some questions are slightly less direct to answer: you ask the order, not the customer |
| Fewer arrows in sequence diagrams; fewer collaborators to set up in a test | A risk of over-forwarding, if functions are added by part instead of by intent |
Common mistakes
Section titled “Common mistakes”- Counting dots. Splitting a chain into variables hides the problem without fixing it. Chains through values, builders, and pipelines are fine.
- Forwarding every getter.
customer_home,customer_points,customer_is_premium, … makeOrdera mirror ofCustomer. Forward by intent. - Returning non-const references to parts.
Membership& membership()invites everyone to change the membership. Return values or const references for questions, and offer commands for changes. - Applying the law to plain data. Wrapping every field of
Addressin a getter so that callers do not “reach into” it adds code and no safety. A value with no rules can show its fields. - Treating the law as absolute. It is a guide to coupling, not a compiler rule. A test that sets up a deep object, or a debugging printout, may reasonably reach in.
When a requirement changes
Section titled “When a requirement changes”Points are doubled in December. The rule itself changes in one
place, Membership::award_for_order, which now needs to know when the
order shipped (syntax-checked sketch, not part of the example):
// The changed rule, still in Membership. std::chrono::year_month_day is a// calendar date (C++20); .month() is its month part.void award_for_order(std::chrono::year_month_day shipped_on) { const int base = premium_ ? 20 : 10; // the old rule // Double the base for an order shipped in December, else the base. points_ += shipped_on.month() == std::chrono::December ? base * 2 : base;}The date also has to reach it, so Order::mark_shipped and
Customer::record_shipped_order each gain a shipped_on parameter that
they pass along, and the dispatcher passes the day it ships. To be honest
about the cost: that is three signatures changed. But only one function
holds the rule, the dispatcher still does not know what the rule is, and
the shipping date is a fair thing for mark_shipped to take, because it
is a fact about the shipment. (Where the dispatcher gets “today” from, in
a way tests can control, is the subject of the dependency-injection page.)
In the old design, the doubling would have gone into the dispatcher, next to the
label code, and into any other place that awards points by calling
add_points itself.
Business customers have a separate delivery address. Only
Order::delivery_address (or a new Customer::delivery_address) changes.
The dispatcher still asks the order where to go and does not care how
the answer is found.
Exercise: Refactor a chained call
A library’s lending desk has this code:
// Lends `book` to `member`, or returns false if the member owes more than// 500 cents in fines.class Desk {public: bool lend(Member& member, const Book& book) { // Three calls in a row: the member's account, the account's fines, // then the fines' total. if (member.account().fines().total_cents() > 500) return false; // loans() returns a reference to the account's own vector, so this // push_back adds the book's id straight into the account's loans. member.account().loans().push_back(book.id()); return true; }};Member::account() returns Account&, Account::fines() returns
Fines&, and Account::loans() returns std::vector<BookId>&.
- Which calls break the Law of Demeter, and which are fine?
- Rewrite it with tell, don’t ask.
- The library adds a rule: at most 5 books on loan. Where does it go in your version, and where would it have gone in the original?
Show the explained answer
1. member.account() on its own is fine: member is a parameter.
The problems are the calls on what it returns.
member.account().fines().total_cents() reaches two steps past the
parameter. member.account().loans().push_back(...) is worse: it changes
a vector inside the account directly, so nothing can check the borrowing
rules. book.id() is fine: book is a parameter, and BookId is a
value.
2. One possible answer (syntax-checked, not part of the example).
Fines is folded into Account as a total, to keep it short; BookId
and Book are as before.
// The account owns the borrowing rule and its own loans list. Nobody else// can reach the list, so every loan goes through borrow.class Account {public: // 500 cents or less in fines may borrow; more may not (as in the // original `> 500` check). [[nodiscard]] bool can_borrow() const { return fines_cents_ <= max_fines_cents; } // Checks the rule itself, so a caller that forgets to ask first is // still refused: it throws std::logic_error and adds nothing. void borrow(BookId book) { if (!can_borrow()) throw std::logic_error("member may not borrow"); loans_.push_back(book); } void add_fine(int cents) { fines_cents_ += cents; }
private: static constexpr int max_fines_cents = 500; int fines_cents_ = 0; std::vector<BookId> loans_;};
// The member forwards to its account, so the desk never sees the account.class Member {public: [[nodiscard]] bool can_borrow() const { return account_.can_borrow(); } void borrow(BookId book) { account_.borrow(book); }
private: Account account_;};
// The desk talks only to its parameters: it asks the member, then tells// the member to borrow. It asks first so that it can return false instead// of catching the exception that borrow would throw.class Desk {public: bool lend(Member& member, const Book& book) { if (!member.can_borrow()) return false; member.borrow(book.id()); return true; }};Member::can_borrow and Member::borrow forward to the account, but by
intent: they say what the desk needs. The account no longer hands out its
loans vector, so borrow can refuse when the rules say no, even if a
future caller forgets to ask first.
An even shorter form is one command, bool Member::try_borrow(BookId),
which checks and borrows in one step; lend becomes
return member.try_borrow(book.id());. That is tell, don’t ask in its
purest form. Keeping can_borrow as well is useful when the desk must
show “may not borrow” before a book is scanned.
3. In your version, it is one more condition in Account::can_borrow:
// Inside Account. std::size_t, because loans_.size() returns that type.static constexpr std::size_t max_loans = 5; // new// ... and the body of can_borrow becomes:// fines within the limit AND fewer than 5 books out (so a 6th is refused).return fines_cents_ <= max_fines_cents && loans_.size() < max_loans;Because borrow also calls can_borrow, no caller changes. In the original, it would have gone into Desk::lend, and into
every other place that pushed onto the loans vector directly, such as an
online renewal page, with nothing to stop one of them from being missed.
Summary
Section titled “Summary”- The Law of Demeter: a function talks to itself, its parameters, objects it creates, and its own data members, not to objects those returned.
- A train wreck such as
order.customer().membership().add_points(20)couples a caller to the structure of classes it does not own. Count the knowledge, not the dots. - Tell, don’t ask fixes it: move the decision to the object that owns the data, and give it a command that can protect its rules.
- Forward by intent, not by part. Names like
delivery_address()andmark_shipped()survive changes;customer_home()does not. - The law does not apply to plain values, fluent builders, range pipelines, or data structures that are meant to be walked.