is a mini series on writing maintainable code without pulling your hair out. Click here for . OOT Object Oriented trick #1 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 before we anything. Wouldn’t it look better like this: ask then ask then ask tell obj.doSomething(); The call to propagates outwards till it get’s to . These long chains of queries, called train wrecks, violate something called the Law of Demeter. doSomething() Z 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 has. It knows has an , has a , has a and that 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. obj.getX().getY().getZ().doSomething() obj X X Y Y Z Z “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 principle with these set of rules: Tell Don’t Ask You may call methods of objects that are:1. Passed as arguments2. Created locally3. Instance variables4. Globals Example Here violated the LoD. The most obvious fix is to delegate/ : account.getPlan().getPrice() tell 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 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 because it’s so easy to violate. But the benefits are obvious, any function that follows this rule, any function that instead of is decoupled from its surroundings. Suggestion of Demeter “tells” “asks” 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 system, Tell Don’t Ask 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.
Share Your Thoughts