Law of Demeter
The Law of Demeter (LoD), or “principle of least knowledge”, says a method should only talk to its immediate friends: its own fields, its parameters, objects it creates, and its direct component objects – not objects it reaches by chaining through one of those.
Colloquially: don’t talk to strangers. A chain like a.getB().getC().doThing() reaches past B to get to C, which makes the caller depend on B’s internal shape as well as C’s.
- This is a concrete way to keep coupling low: every “stranger” you reach through a chain is another thing your code now depends on.
- It also affects modules: a module that respects the Law of Demeter exposes behavior instead of exposing the objects it’s built from.
- A caller that reaches past
BtoChas, in effect, givenBno entry point of its own: it treatsBas a hallway to walk through rather than a place with a name.