Member-only story
Demeter’s Law: Don’t talk to strangers!
Software Engineering Principles

The Law of Demeter (LoD) or principle of least knowledge is a design guideline for developing software, particularly object-oriented programs.
— Wikipedia
This law was proposed by Ian Holland in 1987. Holland and colleagues were programming a system called Demeter using oriented object programming. During the development of the system, they realized that the code that fulfilled a series of rules was less coupled.
Demeter’s law is known as “don’t talk to strangers” because:
- Each unit should have only limited knowledge about other units — only units “closely” related to the current unit.
- Each unit should only talk to its friends — don’t talk to strangers.
- Only talk to your immediate friends.
More formally, the Law of Demeter requires that a method m of an object O may only invoke the methods of the following kinds of objects:
- O itself.
- m’s parameters.
- Any objects created/instantiated within m.
- O’s direct component objects.
- A global variable, accessible by O, in the scope of m.
In summary, all of the rules above can be summarized by saying you should avoid invoking methods of a member object returned by another method. In modern object-oriented languages the identifier used is dot
or ->
. Therefore Demeter's law is violated when the code has more than one step between classes. For example, the following code shows an example in which Demeter's law is violated:

In this case, an object a
from the A class can request a method of an object instanced of B class but the object A should not reach object B directly, because that would mean the object A has greater knowledge of object B's internal structure (tight coupling).