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.
We’ve all seen long chain of functions like these:
We ask then ask then ask before we tell anything. Wouldn’t it look better like this:
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 has a
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
account.getPlan().getPrice() violated the LoD. The most obvious fix is to delegate/tell:
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 neighbouring 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.
Biological systems are an example of such systems. Cells don’t ask each other questions, they tell each other what to do. We are an example of a Tell Don’t Ask system, and within us the Law of Demeter prevails.
What are your views? Let’s chat on Twitter.
Click here for trick #3.
If you liked this post, please hit the little heart! ❤
As always, this post was inspired by Uncle Bob and his book Clean Code.
Hacker Noon is how hackers start their afternoons. We’re a part of the @AMI family. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!