Law of Demeter

The Law of Demeter is an implementation of loose coupling, specifically in object oriented programming languages.

It’s commonly explained as follow…

  • Object A may call methods on object B
  • Object B may call methods on object C
  • Object A may not reach through object B and call methods on object C.

Rationale

If in the above example, object A did call through to object C then object A would have knowledge of both objects B and C. If A only knows about B and B knows about C, they are less coupled and easier to change/replace.

Examples

Example that breaks the law

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14

  class A {
    public B getB() { return new B(); }
  }

  class B {
    public C getC() { return new C(); }
  }

  class C {
    public String getName() { return "Dave"; }
  }

  new A().getB().getC().getName();

Example that doesn’t break the law

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14

  class A {
    public String getName() { return new B().getName(); }
  }

  class B {
    public String getName() { return new C().getName(); }
  }

  class C {
    public String getName() { return "Dave"; }
  }

  new A().getName();

References