Last updated: Apr 29, 2026
Law of Demeter
Also called the principle of least knowledge. A method should only talk to its immediate friends, not reach through objects to access distant parts of the system.
If you see code like order.getCustomer().getAddress().getZipCode(), that’s violating the Law of Demeter.
Example
Driver reaching through Car to start the engine directly:
class Driver {
drive(car: Car): void {
car.getEngine().start(); // knows too much about Car's internals
}
}
Car should expose behaviour, not its guts:
class Car {
private engine = new Engine();
startEngine(): void {
this.engine.start(); // Car handles its own internals
}
}
class Driver {
drive(car: Car): void {
car.startEngine(); // only talks to its immediate friend
}
}
Now Driver is coupled to Car, not to Car’s Engine. If the engine implementation changes, Driver doesn’t care.
The chaining distinction
Builder chains are not a violation:
builder.setName("Alice").setAge(30).build();
Each call returns the same object type, so we’re not traversing into stranger territory.
The problem is specifically when chaining leaks internal structure by jumping through multiple different object types — a.getB().getC().doSomething() is the red flag.
In Practice
- Expose behaviour, not data — keep fields private and give callers methods that do the work
- Add higher-level methods — if callers repeatedly dig through your object to reach something, put a method on your object that returns exactly what they need
- Use a Facade — when interacting with a complex subsystem, wrap it in a higher-level interface so callers never need to reach inside
- Pass what you need — prefer injecting the specific object a method needs over passing a container it has to dig through