The "Law" of Demeter

07 Oct 2014

The Law of Demeter is a guideline to create better software. I use the term guideline to avoid the controversy that comes with the word law when talking about software. People often bash or ignore this principle because there are no such things as laws in software development, so I’d rather highlight that it’s a guideline intended to help you create better software.

The LoD basically states that an object should talk to “friends” and not “strangers”, that is:

  • Call functions in your own class, or
  • Functions of classes returned by a variable/function in your own class

This enforces hiding the internal structure of your objects, to reduce dependencies and ultimately help you build a codebase resistant to change.

The LoD goes in hand with the principle of Tell-Don’t-Ask, which is about telling objects to perform operations instead of asking them for data for other objects to operate on (often violations of the Law of Demeter).

In the end remember these are all guidelines. Of course there are cases when they don’t apply, so we should understand the reasoning behind them and remember to not use them religiously.