Saturday, March 26, 2011

Law of Demeter (LoD)

As a programmer, you want to create software that are loosely coupled. A common rule called Law of Demeter (LoD) can be used in object-oriented software to reduce coupling.

The rule is formulated as: Only talk to your friends. A friend is defined as a variable a piece of code directly knows, ie. an attribute, a local variable or a method parameter.

Now, let's examine the following code:

public void do(ExampleClass c) {
String s = "Hello";


In this example, the code is coupled to three classes: ExampleClass, String, and an unknown class returned by the getSomething() method. Only the first two classes are considered friends.

The code is calling (talking to) methods of two objects: the ExampleClass object and the unknown object.

According to the LoD rule, we don't want to talk to classes that are not our friends. This unknown object is not a friend of us, so we'd rather not call its methods.

We can improve the code using the Law of Demeter like this:

public void do(ExampleClass c) {
String s = "Hello";


A new method is created in ExampleClass in order to take over the responsibility for passing a String to the unknown object. The improved example is coupled to two classes now.

No comments:

Post a Comment