The Law of Demeter for functions states:

A method "M" of an object "O" should invoke only the methods of the following kinds of objects:

  1. itself
  2. its parameters
  3. any objects it creates/instantiates
  4. its direct component objects

Demeter is a research project at Northeastern University, lead by Dr. Karl Lieberherr. The term "Law of Demeter" refers to the paper "Assuring good style for object-oriented programs " by Lieberherr, Karl. J. and Holland, I., Which appeared in IEEE Software, in 1989.

In computer programming, the law of Demeter is an object-oriented extension to the idea that using local variables is good, and using global variables is bad. The law lists which kind of variables are OK, and the rest are then bad. Bad in that that they introduce unwanted coupling and make the code harder to understand.

The Law of Demeter is named after the Demeter System(tm), which provides a high-level interface to class-based OO systems, and the Demeter Research Group at Northeastern U, which develops the system.

My usual practical application of the Law of Demeter in an object-oriented program is that any calls of the form OwnedObject.SubObject.DoSomeOperation(); are bad. They should be rewritten as OwnedObject.DoSomeOperation(); with a method DoSomeOperation written on OwnedObject that forwards the request to its SubObject. In terms of the law of Demeter, SubObject is an owned object of the current object method, but not a direct one like OwnedObject so you shouldn't touch it.

The reason for this is simple; it reduces the coupling that other code has on the internal details of how on OwnedObject works, and allows you to change OwnedObject more easily.

In practice it also makes a more robust program. The code in OwnedObject.DoSomeOperation often ends up as more than just a one-liner to forward the request to SubObject, it may contain assert statements and even program logic that decides where to forward the request. This is good, as it can be changed in one place without the rest of the program minding.

This is really just good encapsulation. You ask an object to do something, and it does it as it best sees fit without you having to know how. In many cases this is to simply forward the request to one of its subsystems.

A related rule-of-thumb is that any block of code that works exclusively with one object should most likely be promoted to being a method on that object.

For instance:
AnObject.setSomeValue(AnObject.getSomeValue() + 1);
if (AnObject.getSomeValue() > AnObject.getSomeOtherValue())

This should definitely be recast as a method of AnObject as it will take on a more readable form there, and you may want to reuse this block of code. This is really just good program decomposition into procedures.

Log in or registerto write something here or to contact authors.