Law of Demeter (Principle of Least Knowledge)¶
Objects should only communicate with their immediate collaborators, because reaching through objects to access distant state creates hidden coupling chains.
Tension Addressed¶
Flexibility vs. Simplicity
Recognizable As¶
Method chains like a.getB().getC().doSomething() as violations; objects that only call methods on parameters, fields, or objects they create; wrapper methods that encapsulate navigation
Canonical Sources¶
Lieberherr et al., "Object-Oriented Programming: An Objective Sense of Style" (1988)
Transfers To¶
API Design (encapsulated navigation), Microservices (service boundaries), Data Access (repository pattern)
Violations create coupling to the structure of the object graph. When B's structure changes, code that navigates through B to reach C must also change, even though it never directly uses B.
Related Concepts¶
- Coupling - Software Architecture