The are
no real laws in programming, and that’s sort of the only law. Law of
Demeter (LoD) is more of a guideline than a principle to help reduce
coupling between components.
Train Wrecks
We’ve all seen long chain of functions like these:
obj.getX() .getY() .getZ() .doSomething();
We ask then ask then ask before we tell anything. Wouldn’t it look better like this:
obj.doSomething();
The call to
doSomething()
propagates outwards till it get’s to Z
. These long chains of queries, called train wrecks, violate something called the Law of Demeter.Law of Demeter
LoD tells us that it is a bad idea for single functions to know the entire navigation structure of the system.
Consider how much knowledge
obj.getX().getY().getZ().doSomething()
has. It knows obj
has an X
, X
has a Y
, Y
has a Z
and that Z
can do something. That’s a huge amount of knowledge that this line has
and it couples the function that contains it to too much of the whole
system.“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.”
When applied to object oriented programs, LoD formalizes the Tell Don’t Ask principle with these set of rules:
You may call methods of objects that are:
1. Passed as arguments
2. Created locally
3. Instance variables
4. Globals
Summary
We
don’t want our functions to know about the entire object map of the
system. Individual functions should have a limited amount of knowledge.
We want to tell our neighboring objects what we need to have done and
depend on them to propagate that message outwards to the appropriate
destination.
Following this rule is very hard. Hence it is even been called as the Suggestion of Demeter because it’s so easy to violate. But the benefits are obvious, any function that follows this rule, any function that “tells” instead of “asks” is decoupled from its surroundings.
source: Object Oriented Tricks: #2 Law of Demeter
No comments:
Post a Comment