What is the Law of Demeter?
Learn the Law of Demeter — least knowledge, train-wreck method chains, and reducing coupling — with a Java refactoring example.
Expected Interview Answer
The Law of Demeter, also called the principle of least knowledge, states that a method should only call methods on itself, its own fields, its parameters, or objects it directly creates — never on objects returned by those objects, to avoid chaining through unrelated internals.
It is informally summarized as "only talk to your immediate friends, not strangers," and violations are recognizable as long chains like a.getB().getC().doSomething(), often nicknamed train-wreck code. Following it means an object exposes methods that do work on its own behalf rather than exposing internal collaborators for the caller to reach through, which reduces coupling between distant parts of a system. This makes code more resilient to change, because a caller no longer breaks when an internal structure two or three levels deep is refactored. The trade-off is that strict adherence can lead to many small wrapper methods, so it is applied pragmatically rather than as an absolute rule.
- Reduces coupling between unrelated parts of the codebase
- Limits the blast radius of internal refactors
- Encourages objects to do work for callers instead of exposing internals
- Makes dependencies between classes easier to reason about
AI Mentor Explanation
A team manager asks the captain to arrange training, and the captain arranges it directly rather than the manager reaching past the captain to instruct individual players’ personal trainers. The manager only ever talks to the captain, never chaining through to the captain’s contacts’ contacts. That is the Law of Demeter: talk only to your immediate collaborator, never reach through it into objects it happens to know about.
Step-by-Step Explanation
Step 1
Identify direct collaborators
List the objects a method legitimately knows about: itself, its fields, its parameters, and locally created objects.
Step 2
Spot chained calls
Look for call chains like a.getB().getC().doX(), which reach through unrelated internal objects.
Step 3
Add a delegating method
Give the immediate collaborator a method that performs the work on the caller's behalf, instead of exposing its internals.
Step 4
Depend only on the immediate object
Replace the chain with a single call to the immediate collaborator's new method.
What Interviewer Expects
- A correct statement of the rule: talk to friends, not strangers
- Recognition of train-wreck method chains as the classic violation
- Understanding of why it reduces coupling and fragility
- Awareness that it is a guideline, not an absolute rule, and can be over-applied
Common Mistakes
- Applying the rule so strictly that it produces excessive trivial wrapper methods
- Confusing it with the Single Responsibility Principle
- Not being able to identify a train-wreck chain in real code
- Thinking it forbids all method chaining, including fluent builder APIs
Best Answer (HR Friendly)
“The Law of Demeter says a piece of code should only talk to objects it directly knows about — itself, its fields, its parameters — and not reach through those objects into things they happen to hold internally. It keeps different parts of a system loosely coupled, so a change deep inside one object does not ripple out and break code far away that never should have known about that internal detail.”
Code Example
// Violation: train-wreck chain reaching through unrelated internals
class Order {
Customer customer;
Customer getCustomer() { return customer; }
}
class Customer {
Wallet wallet;
Wallet getWallet() { return wallet; }
}
class Wallet {
void charge(double amount) { System.out.println("Charged " + amount); }
}
// order.getCustomer().getWallet().charge(50.0); // violates the law
// Respecting the law: Order delegates the work for the caller
class OrderFixed {
Customer customer;
void chargeCustomer(double amount) {
customer.chargeWallet(amount); // Order talks only to its direct field
}
}
class CustomerFixed {
Wallet wallet;
void chargeWallet(double amount) {
wallet.charge(amount); // Customer talks only to its own field
}
}Follow-up Questions
- How would you refactor a train-wreck method chain to comply with the Law of Demeter?
- Does the Law of Demeter conflict with fluent builder-style APIs?
- How does the Law of Demeter relate to coupling and cohesion?
- Can strict adherence to the Law of Demeter hurt code readability?
MCQ Practice
1. The Law of Demeter is also commonly known as?
The Law of Demeter is informally called the principle of least knowledge — talk only to immediate collaborators.
2. Which of the following is a classic sign of a Law of Demeter violation?
Chained calls that reach through intermediate objects into their internals are the classic "train wreck" violation.
3. What is a legitimate object for a method to call under the Law of Demeter?
Parameters passed directly to the method are legitimate immediate collaborators under the Law of Demeter.
Flash Cards
Law of Demeter in one line? — Only call methods on your immediate collaborators, never chain into objects they internally hold.
Informal nickname? — Principle of least knowledge — talk to friends, not strangers.
Classic violation pattern? — A train-wreck chain like a.getB().getC().doSomething().
Main benefit? — Reduces coupling so internal refactors do not ripple out to distant callers.