If you want to walk your dog, you don’t command your dog’s legs to walk. Instead you command the dog and trust that it takes care of its legs itself.

Only talk to your immediate friends.

In modern program languages that use dot as field identifier, use only one dot.

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:

  1. O itself
  2. M‘s parameters
  3. any objects created/instantiated within M
  4. O‘s direct component objects

That summarizes the whole Law Of Demeter, but maybe some more information will enlighten you more… icon smile Law Of Demeter

The purpose of the Law Of Demeter is to minimize coupling between modules. It reduces the size of the response set in the calling class and this tends to reduce errors (a response set is the number of functions directly invoked by methods of the class).

An example in a real programming language makes it all clear for me:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Demeter
{
  private AClass a;
 
  private int func() { return 1; }
 
  public Demeter(BClass b)
  {
    CClass c = new CClass();
 
    /**
    * The law of demeter for functions states that any method
    * of an object should call only methods belonging to:
    */
 
    //Itself
    int f = func();
 
    //Any parameters that were passed in to the method
    b.invert();
 
    //Any objects it created
    a = new AClass();
    a.setActive();
 
    //Any directly held component objects
    c.print();
  }
}

Advantages:

  • It’ll make your code more maintainable and adaptable. Since coupling is minimized, object containers can be changed without reworking their callers.

Disadvantages:

  • It sometimes requiers to write a great deal of small wrapper methods to propagate method calls to the components or subcontractors. As a result, the class’s interface becomes rather bulky and performance can decrease. Reversing the Law of Demeter and tightly coupling modules may give you performance gain.
pixel Law Of Demeter
No TweetBacks yet. (Be the first to Tweet this post)