← All Quizzes
What is the Law of Demeter (principle of least knowledge)?
Explanation
The Law of Demeter (LoD), or principle of least knowledge, states that an object should only interact with its immediate collaborators: itself, its fields, method parameters, and objects it creates. It should not chain method calls through returned objects (e.g., a.getB().getC().doSomething()). This reduces coupling: changes in distant objects have less impact. While strict adherence can create excessive wrapper methods, the principle improves encapsulation and maintainability. Violations (train wrecks) indicate tight coupling and should be refactored by moving behavior to the appropriate object.