• Post Reply Bookmark Topic Watch Topic
  • New Topic

Law of Demeter and managing complexity  RSS feed

 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the replies. You both helped me realize that I'm probably overthinking this stuff. I need some pie.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!