The Law of Demeter

By Deane Barker on August 17, 2005

Law of Demeter: I just finished reading “The Pragmatic Programmer” by Dave Thomas. I didn’t think the book was all that good (see below), but it did talk about a really great principle that I’ve seen articlulated numerous times before.

The Law of Demeter (LoD) is a simple style rule for designing object-oriented systems. “Only talk to your friends” is the motto.

Essentially, a method can only call or manipulate four things:

  1. Itself
  2. Objects passed into it as parameters
  3. Objects it creates inside itself
  4. Any “directly held component objects”

This isn’t new —

Thomas himself implies this law when he discusses “orthoganality” and “decoupling” earlier in the book. Steve McConnell pushes and pushes this concept in his books when he discusses “code hiding” and not allowing objects to “know too much” about each other. And Eric Raymond is famous for his “small pieces, loosely joined” refrain.

I’ve broken the Law of Demeter before and paid for it. You eventually get so many intra-method references to extra-method objects that you may as well just make everything a global variable. And — as McConnell has so eloquently stated — “the road to Hell is paved with global variables.”

(As for “The Pragmatic Programmer” — I’m surprised that I was so disappointed with this book. I’m reading another book by Dave Thomas right now — “Programming Ruby” (“the pickaxe book”) — and it’s the best “learn a new language” book I’ve ever read. Most likely the best language-specific programming book I’ve ever read. Strange.)



  1. I thought about two more things here:

    1. I tend to make my database connection global, so I would break the law here pretty quickly. I don’t do too many global variables, but a database connection is one of them.

    2. There would have to be a script or something that could verify if the law was honored in a an app. It could parse all the files and verify what was being called from where and spank you with an error if you violated the law. That’d be a handy thing.

  2. I had the same reaction to the Pragmatic Programmer, I wanted more detail. I was comparing it to Code Complete by Steve McConnell, which does have a ton of detail. I think the two books have similar ideas but different audiences. If you have the time and interest stick with McConnell.

    I’m reading another Prag Programmer book right now, Ship It! It’s good so far, but I’m sure I’ll compare it to McConnell’s Rapid Development.

Comments are closed. If you have something you really want to say, tweet @gadgetopia.