Concept

Law of Demeter

Definition

The Law of Demeter, sometimes called the principle of least knowledge, says a method should only talk to its immediate collaborators: its own object, objects it creates, objects passed to it as parameters, and the direct components it holds. It should not reach through one object to manipulate a second object hidden inside the first.

A common symptom of a violation is a chain of accessor calls that walks deep into another object's structure. Each link in that chain encodes an assumption about how a distant object is built, and every assumption is a thread that can snap when that distant object changes.

Why it matters

How it works

In practice, you replace a long navigation chain with a request to the nearest object: ask it to perform the work, rather than handing you the inner object so you can do the work yourself. The nearest object then becomes responsible for delegating inward. This shifts knowledge of structure to the place that already owns that structure.

The trade-off is a proliferation of small forwarding methods. Treat the law as a guide: tighten coupling-sensitive boundaries, and relax it for stable data structures where deep access is harmless.

Where it goes next

Continue exploring

Tags