Thursday, October 13, 2011

Law of Demeter (LoD)

The LoD can be summarized as, "Each unit should only use a limited set of other units: only units "closely" related to the current unit". In other words "each unit should only talk to its friends, and not to strangers". The main goal with the LoD is to organized and reduce dependencies between classes. The benefit is loose coupling because a class only knows about its neighbors.

The more formal definition of the LoD states that "Inside of a method M of a class C, data can be accessed in and messages can be sent to only the following objects (namely, method M of an object O may only invoke the methods of the following kinds of objects):

  • Parameters of method M
  • (itself)this, super
  • Data fields (data members) of class C
  • Objects created by functions called by M
  • Global Variables
  • Temporary variables created in method M
Lets look at an example below to show some of the suggestions mentioned above.
 public class Demeter { 

      private A a; 
      private B b; 
       
      // Any method of an object should call only methods  
      // belonging to 
      public void example(B b) { 
           C c = new C(); 
           this.b = b;         // itself 
           int num = f();           
           b.invert();         // passed parameters 
           a = new A(); 
           a.setActive();      // directly held component objects 
           c.print();          // objects created in method  
      } 
       
      public int f() { 
           //implementation omitted 
      } 
 }  

The LoD can also be stated as "use only one dot". What that means is that we can do something like this: foo.someMethod(), however, x.foo.someMethod() will break the LoD.

No comments:

Post a Comment