Law of Demeter | KISS digital

Adam Kubiczek

A co-founder and managing partner of KISS digital.

13 February 2017

Law of Demeter

postMainImage

Just as a short introduction: Law of Demeter is a rule that applies to object-oriented programming. It 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, let’s give it a go, shall we:

class Foo {
  public void bar(SomeObject o)
  {
    //you can:
    o.setResult(this.countResult());

    AnotherObject o2 = new AnotherObject();
    o2.append(o);

    //but you can't:
    o2.popObject().delete();
  } 
}

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 grow class interfaces.

It is evident that there is a problem. So, should we practise this law or not?

The short answer is: yes. The long answer is: we should keep the Law of Demeter in mind, and use it more 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? ;)

Adam Kubiczek

A co-founder and managing partner of KISS digital. Has a long-term experience as a software developer and a team leader.