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:
- Objects passed into it as parameters
- Objects it creates inside itself
- 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.)