From the wikipedia.org article on the Law of Demeter:
More formally, the Law of Demeter for functions requires that any method M of an object O may only invoke the methods of the following kinds of objects:
2. its parameters
3. any objects it creates/instantiates
4. its direct component objects
In particular, an object should avoid invoking methods of a member object returned by another method.
So from my understanding of the LoD the method traverseMap() in the following example is in 'violation':
and instead should be written something like this:
My question is first, am I misinterpreting the LoD with regard to the previous example. And secondly if not, it seems to me that adding the extra method actually increases the complexity of the code, not to mention adding the extra overhead of two extra method calls. Is code like this common in practice?
[ May 02, 2006: Message edited by: Garrett Rowe ]
[ May 03, 2006: Message edited by: Stan James ]
Refactoring this code gives you the same result but does it violate Demeter still?
I claim these two classes are the same, so that their Demeter ranking should be the same. In both cases, A explicitly calls C's method h, and one could argue that A would be simpler if it didn't know details of C.
As far as standard collections go, I make a special case. I think of utility classes as part of the furniture. In the following example, I think of method x and xx as having the same Demeter ranking: they both know B has a method f: