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
Law of Demeter
1:00Reel
More reels
One idea each, a minute or less.
Law of Demeter or tell, don't ask?
0:31Reel
Theory
Read or listen first. About 2 min.
What it is
The Law of Demeter (LoD) is a rule about who a method may talk to. A method may call its own object, its parameters, the objects it creates, and the parts its own object holds. It should not call an object that it only got by asking one of those.
Its other name is the principle of least knowledge. Its motto is: only talk to your friends. The rule limits what a method must know about the shape of the program: who holds whom, and how many steps lie between two objects.
It is called a law, but it is a style rule. It is a fast way to notice a method that knows too much. The answer is rarely a shorter chain. It is a better question to a nearer object.
Why it exists
order.customer.address.city looks like one line of data access. It is three promises: an order has a customer, a customer has exactly one address, an address has a city. When the shop starts selling gift orders with two addresses, every line with this chain is wrong, also in files nobody remembers.
It is also about who decides. When a stall takes the money out of the customer's wallet, the stall must know about coins, cards, limits and empty wallets. When the stall asks the customer to pay, all of that has one home.
And it shows in tests. A test for a method with a four step chain must build four objects to check one line.
A short history
1987
Ian Holland proposes the rule at Northeastern University, during the Demeter project. The project is named after the Greek goddess of agriculture.
1988
Karl Lieberherr, Ian Holland and Arthur Riel publish it at OOPSLA. The paper gives a version for types, which a compiler can check, and a version for objects, which fits the idea better and is harder to check.
1989
Lieberherr and Holland publish Assuring Good Style for Object-Oriented Programs in IEEE Software, September, pages 38 to 48.
2003
Andy Hunt and Dave Thomas call it the pretty good idea of Demeter in IEEE Software: useful, and not a law of nature.
Words to know
- Friend
- An object a method may call: itself, a parameter, an object it made, a part its own object holds.
- Stranger
- An object that a method only knows because a friend returned it.
- Train wreck
- A chain such as a.b().c().d() that walks from object to object.
- Delegation
- A method that answers by calling the next object, so the caller does not have to.
- Fluent interface
- A chain in which each call returns the same object, or a new one of the same kind. It looks like a train wreck and is not one.
- Data structure
- An object whose shape is its purpose: a JSON document, a DTO, a syntax tree.
- Facade
- One object that offers simple calls in front of a group of objects.
- Structural coupling
- Depending on how objects are connected, and not only on what they can do.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
Understand it
Start here
Hand over coins, never your pocket
The stall knows one thing about a customer: you can ask them to pay.
The rule
Four kinds of friends
Take a method m of an object o. These are the objects m may call.
Who may I talk to?
Myself
self.total(). My own methods and my own fields.What I was handed
customer.pay(price), wherecustomeris a parameter of this method.What I made
receipt = Receipt(); receipt.add(line). I created it, so I know it.My own parts
self.method.take(price). A field of my object, or an element of my own collection.
class Method: def __init__(self, coins): self.coins = coins def take(self, n): self.coins -= nclass Customer: def __init__(self, method): self.method = method def pay(self, n): self.method.take(n) # my own partclass Receipt: def __init__(self): self.lines = [] def add(self, line): self.lines.append(line)class Stall: def price(self): return 3 def sell(self, customer): n = self.price() # myself customer.pay(n) # a parameter receipt = Receipt() receipt.add("pear") # I made it return receipt def sell_badly(self, customer): customer.method.coins -= 3 # a stranger's fieldsam = Customer(Method(10))Stall().sell(sam)Stall().sell_badly(sam)print(sam.method.coins)The smell
The train wreck
A program needs the city of an order. The data is there, so the first solution walks to it. Each step looks harmless. Together they write the whole object graph into the caller.
What each step adds
| Code so far | The caller now knows | Types it depends on |
|---|---|---|
order | It has an order | Order |
.getCustomer() | Orders have one customer | Order, Customer |
.getAddress() | Customers have one address | Order, Customer, Address |
.getCity() | Addresses keep a city as text | Order, Customer, Address |
The bad design: every caller knows the graph
1/4One honest dependency
The processor is handed an order. That is a parameter, so a friend.
usesdepends onhas (lives on)owns (dies together)
The good design: one question, passed inward
1/4Ask for the result
The processor asks the order for a city. It does not ask for the way to the city.
useshas (lives on)owns (dies together)
At run time
Who speaks to whom
Before: one caller talks to three objects
After: the question travels inward
A second picture
The recipe at the party
One friend, no strangers.
Not a dot counter
Three things the rule does not forbid
A popular short form is the one dot rule: object.method() is good and a.b().c().d() is suspicious. It is a good smoke alarm and a bad judge. The question is never how many dots, but whose insides you need to know.
| Code | Dots | Verdict | Reason |
|---|---|---|---|
self.method.take(5) | 2 | Fine | My own part |
words.filter(f).map(g).toList() | 3 | Fine | Each call returns a stream: the same kind of object |
response.body.user.name on parsed JSON | 3 | Fine at the edge | The shape is a published format. Translate it once, near the edge |
c = order.customer then c.address | 1 per line | Violation | The chain is only cut into lines |
order.getCustomer().getAddress() | 2 | Violation | Walks through two objects' insides |
order?.customer?.address | 2 | Violation | The question mark hides the error and keeps the knowledge |
Is this chain a problem?
Repairs
Four ways to remove a chain
- 1
Delegate
Add
shippingCity()to the order. Good when several callers want the same answer. - 2
Move the work
Often the caller wants the city only to compute something. Move the computation:
order.shippingCost(rates). This is tell, don't ask, and it usually beats delegation. - 3
Pass the needed value
If the caller needs a city, let its parameter be a city. Whoever has it already passes it in.
- 4
Put a facade in front
If many callers need many answers from a group of classes, give the group one door. See Facade.
// Before: four levels of somebody else's dataclass BadNotifications { confirm(order: any) { const email = order.customer.profile.contactInfo.email; const name = order.customer.profile.personalInfo.firstName; const phone = order.customer.profile.contactInfo.phone; this.send("Hi " + name + ", your order is confirmed!", email, phone); } send(text: string, email: string, phone: string) {}}// After: it names what it needs, and the caller supplies itinterface Recipient { name: string; email: string;}class Notifications { constructor(private send: (to: string, text: string) => void) {} confirm(to: Recipient) { this.send(to.email, "Hi " + to.name + ", your order is confirmed!"); }}// composition: notifications.confirm(order.recipient())The processor needs the shipping city. What do you write?
BreaksCut the chain into variables
- How
customer = order.customer,address = customer.address,city = address.city.- Limit
- Same three dependencies on three lines. Any change of the graph still hits this method.
- Choose when
- Never as a fix.
WorksDelegate step by step
- How
order.shippingCity()callscustomer.shippingCity(), which callsaddress.city().- Limit
- Each new field adds a method in two classes. Twenty fields make a wide, dull interface.
- Choose when
- A few stable answers that many callers need.
StrongAsk for the decision
- How
- Find out what the city is for. If it chooses a warehouse, write
order.chooseWarehouse(warehouses)and let the order compare. - Limit
- Needs thought about who owns the decision. Reports still need plain data.
- Choose when
- The caller asks, then decides. That is most of the time.
What you get
Benefits and the bill
Loose coupling
Callers do not know how other objects are built.
Easier refactoring
Insides can change without a search through the project.
Better encapsulation
An object that hands out no parts keeps its rules.
Simpler tests
One stand-in object instead of a chain of them.
Clearer intent
shippingCity()says what, a chain says how.The bill
More small methods, and one more place to look when you follow a call.
Neighbours
How it fits with other ideas
| Idea | Question it asks | Relation |
|---|---|---|
| Tell, don't ask | Who decides? | Removes most chains by moving the decision |
| Encapsulation | Who may change my data? | Getters that return parts make chains possible |
| Reducing coupling | How much do I know about others? | LoD is one special, easy to see case |
| Interface segregation | How many methods do I see? | The cure when delegation makes a class wide |
| Facade | What is the simple door? | LoD for a group of classes |
Summary
The whole topic in one minute.
Friends are yourself, your parameters, what you create and your own parts. Anything else that a friend hands out is a stranger. Ask the friend for the result, not for the stranger.
Do not count dots. self.method.take(5) has two dots and is fine, and c = order.customer on its own line hides a chain without removing it. Plain data and fluent interfaces are no violation.
The rule has a price: more small methods. When one class collects twenty of them, the behaviour sits in the wrong place, or the caller needs a narrower view.
- A method talks to itself, its parameters, what it makes, and its own parts.
- A chain writes the object graph into the caller.
- Ask the near object for the result, or better, give it the decision.
- Do not count dots: fluent chains and plain data are fine.
- Chains cut into variables are still chains.
- If delegation makes a class huge, the behaviour is in the wrong class.
Sources
- A general formulation of the Law of Demeter, Northeastern University
- Lieberherr, Holland, Riel: Object-Oriented Programming, An Objective Sense of Style (OOPSLA 1988)
- Hunt and Thomas: The Art of Enbugging, IEEE Software 2003
- PMD: LawOfDemeter rule
- Rails: Module#delegate
- Kotlin: Delegation
- Spring: JdbcTemplate
- Kubernetes: Service