Law of Demeter

Just for the introduction – Law of Demeter is a rule that applied to object-oriented programming, helps us keep a code more maintainable and adaptable, by making classes and methods less dependent on other objects.

Let me copy & paste a few rules from Wikipedia:

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 itself
* m’s parameters
* Any objects created/instantiated within m
* O’s direct component objects

So, for instance, let’s take a class:

class Foo {
  public void bar(SomeObject o)
    //you can:

    AnotherObject o2 = new AnotherObject();

    //but you can't:

So far, so good. We have the loosely coupled class that can be easy refactored or re-used. However, one can say using Law Of Demeter tends to multiply auxiliary methods in classes and to grow class interfaces.

It is evident that this is some problem. So should we practice this law or not?

The short answer is: yes. The long answer is: we should keep the LoD in mind, and use it regularly as a starting point. When our class grows unnaturally and beyond reasonable limits, then and only then it is time to add some dependency and to worsen coupling. All right? ;)