Law of Demeter

A method talks only to its own object, its parameters, the objects it creates and its own fields. It never reaches through one object to work on the insides of another.

Overview

The Law of Demeter is a rule about who a method may talk to. It was found at Northeastern University in 1987 by Ian Holland, while the team built the Demeter system, and published by Lieberherr, Holland and Riel at OOPSLA in 1988. The short form is: only talk to your immediate friends. The point is coupling. Every object your code reaches into is an object whose structure your code now depends on.

What the rule says

Inside a method, you may call methods on a short list of things. Anything else is a stranger, and you should not send it messages. Here is the list, with an example of each from inside Order.total().

  • The object itself: self.apply_discount().
  • The method's parameters: coupon.rate(), when coupon was passed in.
  • Objects the method creates: Money(0).add(...).
  • The object's own fields: self.lines.
  • Objects returned by the object's own methods: self.customer(). This one belongs to the class form of the rule.

The 1988 paper gives two forms. The object form says what we really want: talk only to objects you hold directly. It cannot be checked by a compiler. The class form, which tools such as PMD implement, checks the types instead, and is what most people mean by the rule.

Interview questions

  • How do you identify Law of Demeter violations?
  • How do you fix violations without creating a pile of wrapper methods?
  • When is a chain of calls acceptable?
  • How does the Law of Demeter relate to encapsulation and coupling?
  • Does the rule apply between services, not just objects?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio