Law of Demeter

Go to the Wiki Overview

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 B to C has, in effect, given B no entry point of its own: it treats B as a hallway to walk through rather than a place with a name.