Back to Academy
coding principles
Law of Demeter
The Law of Demeter (LoD), also known as the principle of least knowledge, states that a unit should only talk to its immediate friends — not to strangers. In practice this means an object's method should only call methods on: the object itself, its parameters, objects it creates, and its direct component objects. Chaining through multiple layers (a.getB().getC().doSomething()) creates tight coupling to the internal structure of collaborators, making refactoring difficult and fragile.
Use Cases
- •Avoiding deep method chains that expose internal structure of objects
- •Creating facade methods that encapsulate multi-step operations on nested objects
- •Reducing coupling between modules so internal changes do not cascade through the system
- •Designing APIs that hide implementation details behind simple, intention-revealing interfaces
Visualization
Implementation
Output
Click "Run Code" to see output...