I've been lurking around the 'Ranch for some time and I pick up a lot of good stuff. For a while now I've seen sporadic references to the 'Law of Demeter' so after doing some research on it I have some questions about its application. 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:
1. itself 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 ]
Post by:Stan James
, Ranch Hand
Following Demeter isn't really possible 100% of the time. Collections are a prime example. Their whole purpose is to hold some stuff you want back later, so you have to have ways to get stuff out. Still, Demeter is a good guideline along with "Tell, don't ask" to remind you to work at encapsulation and low coupling. Here are some allegedly humorous examples. Some of Knight's Principles tie right in, too. [ May 03, 2006: Message edited by: Stan James ]
Post by:Jeff Albertson
, Ranch Hand
This looks like it violates Demeter with the invocation of h:
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:
Post by:Garrett Rowe
, Ranch Hand
Thanks for the replies. You both helped me realize that I'm probably overthinking this stuff. I need some pie.
This thread has been viewed 684 times.
All times above are in ranch (not your local) time.
The current ranch time is Sep 23, 2018 02:19:41.