Law of Demeter — Clean Code

The Law of Demeter (Holland 1987, Lieberherr and Holland 1989, popularised by Clean Code 2008): talk to close friends, meaning this, parameters, objects you…

You want to know which city Sari's parcel is going to. You ask the courier desk, "Which city is this parcel going to?", and they answer "Leeds". You don't need to know that they open a folder, find the order sheet, then read the third line of the address column. When the courier changes its forms, you still ask the same question. In code, a chain like order.customer.address.city opens that folder itself.

The Law of Demeter (also called the Principle of Least Knowledge) asks code to ask the way you just did: an object should only talk to its close friends, not to its friends' friends. It was born in the Demeter Project at Northeastern University (Ian Holland, 1987), written up formally by Karl Lieberherr and Ian Holland in IEEE Software (1989), and popularised by Robert C. Martin in Clean Code (2008).

Three files, one chain

Raka's T-Shirt Shop now ships parcels. Sari's order:

const order = {
  id: 1,
  customer: {
    name: 'Sari',
    address: { street: '7 Coffee St', city: 'Leeds' },
  },
};

Three functions, in three different files, need the destination city:

// courier.js: the shop has its own courier for Leeds
function pickCourier(order) {
  if (order.customer.address.city === 'Leeds') return 'Raka Courier';
  return 'Express Courier';
}

// estimate.js: delivery time in days
function deliveryDays(order) {
  return order.customer.address.city === 'Leeds' ? 1 : 3;
}

// report.js
function reportLine(order) {
  return 'Order #' + order.id + ' to ' + order.customer.address.city;
}

The output is Raka Courier, 1, Order #1 to Leeds. Everything works. But every dot in order.customer.address.city is one thing the function knows: an order has a customer, a customer has one address, an address has a city. A chain like this, object after object joined by dots, is what Clean Code calls a train wreck: carriages coupled together.

When the address changes shape

Raka wants customers to keep a home and an office address:

customer: {
  name: 'Sari',
  addresses: [
    { label: 'Home', street: '7 Coffee St', city: 'Leeds' },
    { label: 'Office', street: '8 Market St', city: 'Leeds' },
  ],
},

All three functions still read order.customer.address.city. Guess first: does pickCourier(order) now give 'Express Courier', undefined, or an error?

All three functions throw the same error (Chrome's and Node's wording):

TypeError: Cannot read properties of undefined (reading 'city')

An error, not 'Express Courier'. order.customer.address is now undefined, and reading .city from undefined fails. One change to the data's shape forces three files to change, exactly the Shotgun Surgery from the Code Smells lesson. It's worse if someone "protects" the chain with optional chaining, order.customer.address?.city: the error goes away, the result is undefined, and Sari, who lives in Leeds, is shipped through Express Courier without anyone noticing.

Talk to close friends

The rule, as Clean Code puts it: a method f of a class C should only call the methods of

  1. C itself (this),
  2. an object created by f,
  3. an object passed to f as an argument,
  4. an object held in a field of C.

What's not allowed: calling methods on an object returned by one of those, a friend's friend. So the caller just asks order, and each object answers from its own data:

class Customer {
  constructor(data) {
    this.data = data; // the customer's row from the database
  }
  city() {
    return this.data.address.city; // only Customer knows the data's shape
  }
}

class Order {
  constructor(id, customer) {
    this.id = id;
    this.customer = customer;
  }
  shippingCity() {
    return this.customer.city(); // a close friend: Order's field
  }
}

const sari = new Customer({
  name: 'Sari',
  address: { street: '7 Coffee St', city: 'Leeds' },
});
const order = new Order(1, sari);

function pickCourier(order) {
  if (order.shippingCity() === 'Leeds') return 'Raka Courier';
  return 'Express Courier';
}

deliveryDays and reportLine also just call order.shippingCity(). When the address data becomes a list, all three still fail until the code is updated, but the update is one line: city() becomes return this.data.addresses[0].city;. The three callers aren't touched: from 3 places that read the address down to 1. Moving a chain into the object that owns the data is called Hide Delegate (Martin Fowler, Refactoring).

Tell, don't ask

The Law of Demeter's partner is Tell, Don't Ask: tell an object to do something, don't pull its data out to decide outside. Raka's shop has a wallet balance for customers:

// ASK: checkout takes the wallet apart and decides by itself
if (customer.wallet.balance >= total) {
  customer.wallet.balance -= total;
}

// TELL: checkout gives the order, the customer knows the rules
if (customer.canPay(total)) customer.pay(total);

Raka adds a rule: "a frozen wallet can't be used". The ask version: every place that reads wallet.balance has to remember to add a frozen check. The tell version: only canPay in the Customer class changes.

Count types, not dots

Not every run of dots is a violation. What counts is moving to a different type:

Don't become a Middle Man

Going too far has its own smell. An Order full of getCustomerName, getCustomerEmail, getCustomerPhone, getCustomerCity and twenty more methods that only pass the call on to customer is a Middle Man (Fowler): a class whose only work is forwarding. Add methods for the questions callers actually ask (shippingCity, canPay), not for every field there is.

Exercise: getCustomerName and getCustomerCity

The exercise uses classes with getters: Address has getCity(), Customer has getName() and getAddress(), Order has getCustomer(). Add two methods to Order:

getCustomerName() {
  return this.customer.getName();
}
getCustomerCity() {
  return this.customer.getAddress().getCity();
}

The caller then just calls order.getCustomerName() and order.getCustomerCity(), with no order.getCustomer().getAddress() chain. The output is three lines: Budi, Manchester, true (the last from typeof Order.prototype.getCustomerCity === 'function'). Inside Order there is still a short chain to the address, but now in one place. To be strict, like Customer.city() above, give Customer a getCity() method and have Order call this.customer.getCity().

⚠️ Chains that get patched instead of cut

TL;DR: The Law of Demeter (Holland 1987, Lieberherr and Holland 1989, popularised by Clean Code 2008): talk to close friends, meaning this, parameters, objects you create and your own fields, not to the objects they return. order.customer.address.city in three files makes changing address into addresses throw TypeError: Cannot read properties of undefined (reading 'city') in all three; with order.shippingCity() and Customer.city() (Hide Delegate) only one place changes. Tell, Don't Ask: customer.canPay(total) and customer.pay(total), not taking wallet.balance apart outside. Count moves between types, not dots: chains on the same type (Array, String, query builder) are fine, plain data like JSON may be read directly, and order.getCustomer().getBillingAddress().getStreet() is a train wreck. Don't overdo it into a Middle Man. In the exercise: getCustomerName() and getCustomerCity() on Order, output Budi, Manchester, true.

⚡ Train wreck

Write:

  if (order.customer.address.city === 'Leeds') return 'Raka Courier';

Meaning: Every dot in order.customer.address.city is one thing this function knows about someone else's data. A chain of objects joined by dots is called a train wreck.

⚡ When the address changes shape

Guess first: address becomes a list, addresses. Does pickCourier(order) now give 'Express Courier', undefined, or an error?

An error: TypeError: Cannot read properties of undefined (reading 'city'), in all three files at once.

Meaning: One change to the data's shape forces three files to change. Patching it with ?. only makes the result quietly wrong: a parcel for Leeds goes by Express Courier.

⚡ Talk to close friends

Write:

  shippingCity() {
    return this.customer.city(); // a close friend: Order's field
  }

Meaning: The caller just asks order.shippingCity(). When the address changes shape, only one line in Customer.city() is updated. Moving the chain into the object that owns the data is called Hide Delegate.

⚡ Count types, not dots

Meaning: cart.filter(...).map(...) is fine, because every step is still an Array. order.getCustomer().getBillingAddress().getStreet() jumps across four different types, and that's a train wreck. But don't overdo it into a Middle Man that passes on every field.

What you will learn