LoD
Law of Demeter
“Talk only to your immediate friends.”
The Principle of Least Knowledge. A module should not know about the innards of the objects it manipulates.
When to use
When you see a chain of dot accessors (e.g., a.getB().getC().doSomething()).
Why it matters
- Decoupling: Classes are less dependent on the internal structure of strange classes.
- Maintainability: Changing
Class Cdoesn’t breakClass Aif they aren’t directly talking.
Signs of Violation
- “Train Wrecks”:
getObj().getChild().getParam().getValue(). - Excessive number of imports for types that are only used to “get to” other types.
Explanation
Problem
If A talks to B to get C to get D, then A is now coupled to B, C, and D. Any change in the relationship hierarchy breaks A.
Solution
Ask B to do the work, or ask B to give you what you need directly. Don’t reach into B’s pockets.
Real world analogy
When you buy something at a store, you give the cashier your money. You don’t hand your wallet to the cashier and let them dig through it to find the money.
Pros and Cons
| Pros | Cons |
|---|---|
Comparison
- Information Expert: LoD enforces Information Expert (asking the object that has the info).
Code example
Typescript
Bad (Violation)
Good (Adherence)
PHP
Bad (Violation)
Good (Adherence)