Law of Demeter and Tell, Don’t Ask

Somehow last week, can’t remember the context, I came across the Law Of Demeter for the first time, me not having an OOP background.

I followed the rabbit down a few holes and came to appreciate that this is a commonly misunderstood guideline, not a law, and often misinterpreted in terms of counting dots.

The “law” states:

A method of an object should invoke only the methods of the following kinds of

  • itself
  • its parameters
  • any objects it creates / instantiates
  • its direct component objects

Other people have explained it pretty well as follows:

It seems to be just about avoiding dependencies and being tightly coupled – your object should not be dependent on another object’s dependencies.

The references above use the analogy of a paperboy who needs paying by you, the customer.

  • You don’t let the paperboy take the wallet (object) from the customer(object) and take payment (method/attribute manipulation on wallet).
  • The paperboy doesn’t need to know anything about the wallet.
  • All the paperboy cares about is his payment.
  • He doesn’t need to know anything about where the money comes from other than whether he gets his dosh or not.

This is a very artificial example, as the references above acknowledge.

The problem with oversimplistic and contrived examples is they can then raise many “buts” which take away from the point at heart.

Seems to me (but what do I know yet) that the Tell, Don’t Ask principle is aimed at a similar target to Demeter.