Law of Demeter
medium 40 minTalk to your own parts and to what you were handed, and not to the parts inside them.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Objects at run time: who speaks to whom, and who must know about whom.
Operations
A hand in the pocket
The stall takes the money itself. Watch the purse's rule being skipped.
Step 1 of 5
Two objects meet
The stall was handed a customer. The purse is the customer's own part.
Step 1: Two objects meet
class Stall: def sell(self, customer, price): customer.purse.cents -= price self.till += pricesam = Customer(Purse(500))stall.sell(sam, 300)stall.sell(sam, 300)- Good for
- Nothing that lasts
- Costs
- Every seller knows purses
- Types the stall knows
- 2
Look for a minus sign on somebody else's field.
In the real world
The same law of demeter doing real jobs. Pick one and step through it.
Four changes, two designs. The last row is the price.
Step 1 of 4
A purse may not be negative
| With chains | With the law | |
|---|---|---|
| no negative | all sellers | Purse only |
| gift address | ||
| cards | ||
| new question |
With chains each seller has to add the check.
Step 1: A purse may not be negative
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Cutting the chain into lines
majorThe method still knows every type.
Wrongc = order.customera = c.addresscity = a.cityRightcity = order.shipping_city()Changing a stranger's field
criticalNo rule of the owner runs.
Wrongcustomer.purse.cents -= priceRightok = customer.pay(price)A getter for a part
majorIt opens the door again for everybody.
Wrongdef payment_method(self): return self._methodRightdef payment_label(self): return self._method.label()Counting dots
minorA fluent chain needs knowledge of one type.
Wrong# "too many dots"a = words.filter(f)b = a.map(g)Rightwords.filter(f).map(g)Forwarding everything
majorThe order can suddenly close accounts.
Wrongdef __getattr__(self, name): return getattr(self._customer, name)Rightdef shipping_city(self): return self._customer.shipping_city()One query per polite call
majorFifty orders, fifty queries, and nobody sees them.
Wrong[o.shipping_city() for o in orders]Rightbook.shipping_cities() # loads once
Interview tips
Name the friends
- Self
- Parameters
- Any object I make
- My parts
Ask what for
- Does the caller decide with it?
- Then move the decision
- Else delegate or pass the value
Know the exceptions
- Fluent chains
- Plain data
- Parse outside data once
Mind the price
- Group values by purpose
- Narrow interfaces
- Batch for lists