You are not logged in Log in Join
You are here: Home » Members » Phillip J. Eby's Zope Center » My Wikis » ZPatterns Wiki » DemetersLaw

Log in
Name

Password

 
 
HomePage »

DemetersLaw

The Law of Demeter says that if I need to obtain a service from an object's sub-object, I should instead make the request of the parent object and let it propagate the request (by method delegation) to any relevant sub-objects. Thus, objects avoid meddling with other objects' innards.

Stated more formally, the Law of Demeter for functions says that a method "M" of an object "O" should invoke only the the methods of

  • object O
  • direct component objects of O
  • parameters of method M
  • objects created/instantiated by M

In other words code like "a.b.c()" or "a().b().c()" is a bad idea, because it violates InformationHiding by adding information to your method about how other objects are structured. Note that saying things like "d = a.b; d = d.c" isn't any better. Generally speaking, if you have to ask one object for another object, then do something with that second object, it's probably an indication that the intermediate object is missing a method delegation service. You should be able to write "a.b.c()" as "a.bc()", in other words. That is, there should be a bc() method on a, which then invokes self.b.c().

The ZPatterns framework was constructed in fairly strict compliance with this law. While it occasionally leads to tedious creation of methods that do nothing but pass on the call to another object, the reward in simplification, abstraction, and flexibility has been high. In particular, it leads to code where the exact location to change behavior is always known, because nobody messes with anybody else's internals.

Reading law-compliant code does take some getting used to, however. At first glance, classes seem like they're not really doing anything, because the code looks too simple to be doing anything useful. As ../TySarna remarked after we desk-checked some of the first classes we wrote this way, "There's no there there!" But as we've gotten used to the style, non-Demeter code is now beginning to look verbose, overcomplicated, and fragile by comparison.

For more information on the Law of Demeter, including papers, tools, discussions, etc., see http://www.ccs.neu.edu/home/lieber/LoD.html