- 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.
https://www2.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf
More formally, the Law of Demeter for functions requires that a method m
of an object O
may only invoke the methods of the following kinds of objects:
O
itselfm
's parameters- Any objects created/instantiated within
m
O
's direct component objects- A global variable, accessible by
O
, in the scope ofm
In particular, an object should avoid invoking methods of a member object returned by another method. For many modern object oriented languages that use a dot as field identifier, the law can be stated simply as "use only one dot". That is, the code a.b.Method()
breaks the law where a.Method()
does not. As an analogy, when one wants a dog to walk, one does not command the dog's legs to walk directly; instead one commands the dog which then commands its own legs.