Thursday, October 13, 2016

The Law of Demeter

This is a well known software design guideline that helps you write code that is:
  • More readable
  • More testable
  • Less coupled 
It also goes by the following three definitions, ranging from least formal to most formal:

Definition 1

Don't talk to strangers. Only talk to your (immediate) friends. 

Your best friends are Bob, Jane, and Josh. You need help? Talk to them. Don't talk to their friends or their cousins. 

Definition 2

Use only one dot. 

No: SomeObject.doOneThing().doAnotherThing().andAnotherThing()
Yes: SomeObject.doManyThings()

Uncle Bob calls the first NO example a train wreck. Avoid train wrecks. 

Definition 3

Method F of object C may only call methods of objects that are:
  1. C
  2. Ceated by C
  3. Parameters of F
  4. Created by F

Effects of Least Knowledge on Testing, Coupling, Readability


We don't need code samples to consider the implications of this on our code. What all three definitions have in common is that by following them, you're minimizing an objects knowledge of other objects. If you're forced to only talk to your immediate friends, you don't need to know about their friends. If you're only using one dot, you're only ever dealing with the interface of one other object. This is why the Law of Demeter is also known as the Principle of Least Knowledge. 

There's a strong correlation between the amount of knowledge an object has about other objects and the difficulty of testing that object. Think about it. The more things an objects interacts with, the more you have to set up in order to test that objects behaviors. 

When an object has little knowledge about other objects, code also tends to be less coupled. An object with no dependencies and with nothing that depends on it is an object with no coupling. It depends on nothing and nothing depends on it. Systems, however, aren't usually built using a number of completely isolated parts that don't communicate with one another. But the more we can limit the communication between different parts, the less likely any change in one part of that system will affect the rest. 

If you're looking at a code base that adheres to LOD, there's a good chance you'll find it very readable because the less objects know about other objects, the less you have to know when you're trying to understand that object. If you're dealing with a train wreck, to really understand what's happening you have to follow multiple dots and that requires more effort and to change the behavior will require you to understand the interfaces of two or more objects. Again, more mental effort.

No comments:

Post a Comment