Polski

Article · Law of Demeter · Facade

The Law of Demeter: talk only to your friends

The Law of Demeter (principle of least knowledge) through loyalty-point redemption in Halina's pierogi place: call chains vs Tell, Don't Ask, exceptions for fluent interfaces and DTOs, code in C#, TypeScript, Java, Go and Python, and how it relates to encapsulation and coupling metrics.

By · · 16 min read

A customer of Halina's pierogi place pays for an order with loyalty points: 200 points give a 20 zł discount. Meanwhile the checkout code knows the order's entire family tree: order.getCustomer().getLoyaltyAccount().getBalance().getPoints(). The Law of Demeter, also called the Principle of Least Knowledge, says: an object talks only to its immediate collaborators, not to their insides.

1987
Northeastern University – Ian Holland states the principle in the Demeter project
5 → 1
classes the checkout knows – before and after the refactoring
4
kinds of a method's "friends" – its object, parameters, created objects and fields

Where the Law of Demeter comes from

Ian Holland formulated the principle in 1987 in the Demeter project at Northeastern University, led by Karl Lieberherr. The name comes from the project, and the project's name from the Greek goddess of agriculture: the idea was software that "grows" step by step. A year later Lieberherr, Holland and Riel described the principle at the OOPSLA conference. The colloquial version goes: talk only to your friends, don't talk to strangers.

Formally, a method m of an object O may only call methods of these "friends":

FriendExample in Order.redeemPoints
the object O itselfthis.applyDiscount(...)
the parameters of mpoints passed in by the checkout
objects created within mnew Discount(...)
the fields (components) of Othis.customer.redeemPoints(...)

The original formulation also allows global variables in the method's scope – today we treat those as a problem rather than a friend. What is not allowed is calling methods on objects returned by those calls: this.customer.getLoyaltyAccount().redeem(...) is already talking to a stranger.

The problem: a checkout that knows too much

The first version of point redemption was written in the checkout, because "that's where it's needed":

checkout-before.ts
// Before: Checkout reaches through Order → Customer → LoyaltyAccount → Balance.
function redeemPoints(order: Order, points: number): void {
  const balance = order.getCustomer().getLoyaltyAccount().getBalance();
  if (balance.getPoints() < points) throw new Error('Not enough points');

  const discount = points * 10; // 1 point = 10 grosze – a loyalty rule leaked into Checkout
  if (discount > order.getTotal().getGrosze()) throw new Error('Discount larger than the order');

  balance.setPoints(balance.getPoints() - points);
  order.getTotal().setGrosze(order.getTotal().getGrosze() - discount);
}

Such chains are called train wrecks – carriages of dots coupled one after another. Martin Fowler's Refactoring describes them as the Message Chains code smell. What is wrong with them?

  • The checkout knows five classes – the order, the customer, the loyalty account, the balance and the amount – and how they are connected. Any change to that structure breaks the code. The same chain also lived in the mobile app's API and in the admin panel, so when points moved to a separate customer wallet, three places needed fixing.
  • A loyalty-programme rule leaked out. The "1 point = 10 grosze" conversion lives in the checkout, and probably in the mobile app too (see DRY).
  • Ask first, then act. The code reads the balance, decides on its own and writes the result back through setters. The invariant "the balance never goes below zero" is guarded by the caller, not by the object that owns the balance.
  • Mocks returning mocks. To test the checkout you have to build a mock order that returns a mock customer that returns a mock account…
Diagram: Who the checkout knows: before and after the refactoring

The solution: tell, don't ask

Tell, Don't Ask was popularised by Andy Hunt and Dave Thomas in their article The Art of Enbugging (2003): instead of asking an object for its state and deciding on its behalf, tell it what to do. Each object does its part of the work and talks only to its neighbour: the order knows its total and caps the discount, the customer passes the request on to its account, and the account checks the balance and converts the points.

Diagram: Point redemption: everyone talks only to their neighbour

Tell, don't ask – redeeming loyalty points

Loyalty.cs
var order = new Order("A-1042", new Customer("Ania", new LoyaltyAccount(initialPoints: 250)), totalGrosze: 4_590);
order.RedeemPoints(200);  // Checkout talks only to its friend: the order
Console.WriteLine(order); // A-1042: 25.90 zł, Ania has 50 points left

public sealed class LoyaltyAccount(int initialPoints)
{
    private const int GroszePerPoint = 10;
    public int Points { get; private set; } = initialPoints;

    // Tell the account to redeem – don't read its balance and do the maths outside.
    public long Redeem(int points, long maxDiscountGrosze)
    {
        var discount = (long)points * GroszePerPoint;
        if (points > Points) throw new InvalidOperationException("Not enough points");
        if (discount > maxDiscountGrosze) throw new InvalidOperationException("Discount larger than the order");
        Points -= points;
        return discount;
    }
}

public sealed class Customer(string name, LoyaltyAccount loyalty)
{
    public long RedeemPoints(int points, long maxDiscountGrosze) => loyalty.Redeem(points, maxDiscountGrosze);
    public override string ToString() => $"{name} has {loyalty.Points} points left";
}

public sealed class Order(string id, Customer customer, long totalGrosze)
{
    private long _total = totalGrosze;

    public void RedeemPoints(int points) => _total -= customer.RedeemPoints(points, maxDiscountGrosze: _total);

    public override string ToString() => $"{id}: {_total / 100}.{_total % 100:00} zł, {customer}";
}
loyalty.ts
class LoyaltyAccount {
  private static readonly GROSZE_PER_POINT = 10;
  constructor(private points: number) {}

  get balance(): number {
    return this.points;
  }

  // Tell the account to redeem – don't read its balance and do the maths outside.
  redeem(points: number, maxDiscount: number): number {
    const discount = points * LoyaltyAccount.GROSZE_PER_POINT;
    if (points > this.points) throw new Error('Not enough points');
    if (discount > maxDiscount) throw new Error('Discount larger than the order');
    this.points -= points;
    return discount;
  }
}

class Customer {
  constructor(private readonly name: string, private readonly loyalty: LoyaltyAccount) {}
  redeemPoints(points: number, maxDiscount: number): number {
    return this.loyalty.redeem(points, maxDiscount);
  }
  toString(): string {
    return `${this.name} has ${this.loyalty.balance} points left`;
  }
}

class Order {
  constructor(private readonly id: string, private readonly customer: Customer, private total: number) {}
  redeemPoints(points: number): void {
    this.total -= this.customer.redeemPoints(points, this.total);
  }
  toString(): string {
    return `${this.id}: ${(this.total / 100).toFixed(2)} zł, ${this.customer}`;
  }
}

const order = new Order('A-1042', new Customer('Ania', new LoyaltyAccount(250)), 4_590);
order.redeemPoints(200);    // Checkout talks only to its friend: the order
console.log(String(order)); // A-1042: 25.90 zł, Ania has 50 points left
Loyalty.java
public class Loyalty {
    public static void main(String[] args) {
        var order = new Order("A-1042", new Customer("Ania", new LoyaltyAccount(250)), 4_590);
        order.redeemPoints(200);   // Checkout talks only to its friend: the order
        System.out.println(order); // A-1042: 25.90 zł, Ania has 50 points left
    }
}

class LoyaltyAccount {
    private static final int GROSZE_PER_POINT = 10;
    private int points;

    LoyaltyAccount(int points) { this.points = points; }

    int balance() { return points; }

    // Tell the account to redeem – don't read its balance and do the maths outside.
    long redeem(int points, long maxDiscountGrosze) {
        long discount = (long) points * GROSZE_PER_POINT;
        if (points > this.points) throw new IllegalStateException("Not enough points");
        if (discount > maxDiscountGrosze) throw new IllegalStateException("Discount larger than the order");
        this.points -= points;
        return discount;
    }
}

record Customer(String name, LoyaltyAccount loyalty) {
    long redeemPoints(int points, long maxDiscountGrosze) { return loyalty.redeem(points, maxDiscountGrosze); }

    @Override public String toString() { return name + " has " + loyalty.balance() + " points left"; }
}

class Order {
    private final String id;
    private final Customer customer;
    private long total; // grosze

    Order(String id, Customer customer, long total) { this.id = id; this.customer = customer; this.total = total; }

    void redeemPoints(int points) { total -= customer.redeemPoints(points, total); }

    @Override public String toString() { return "%s: %d.%02d zł, %s".formatted(id, total / 100, total % 100, customer); }
}
loyalty.go
package main

import (
	"errors"
	"fmt"
)

const groszePerPoint = 10

var (
	ErrNotEnoughPoints = errors.New("not enough points")
	ErrDiscountTooBig  = errors.New("discount larger than the order")
)

type LoyaltyAccount struct{ points int }

func (a *LoyaltyAccount) Balance() int { return a.points }

// Redeem: tell the account what to do instead of reading its balance.
func (a *LoyaltyAccount) Redeem(points int, maxDiscount int64) (int64, error) {
	discount := int64(points) * groszePerPoint
	if points > a.points {
		return 0, ErrNotEnoughPoints
	}
	if discount > maxDiscount {
		return 0, ErrDiscountTooBig
	}
	a.points -= points
	return discount, nil
}

type Customer struct {
	name    string
	loyalty *LoyaltyAccount
}

func (c *Customer) RedeemPoints(points int, maxDiscount int64) (int64, error) {
	return c.loyalty.Redeem(points, maxDiscount)
}

func (c *Customer) String() string { return fmt.Sprintf("%s has %d points left", c.name, c.loyalty.Balance()) }

type Order struct {
	id       string
	customer *Customer
	total    int64 // grosze
}

func (o *Order) RedeemPoints(points int) error {
	discount, err := o.customer.RedeemPoints(points, o.total)
	if err != nil {
		return err
	}
	o.total -= discount
	return nil
}

func (o *Order) String() string {
	return fmt.Sprintf("%s: %d.%02d zł, %s", o.id, o.total/100, o.total%100, o.customer)
}

func main() {
	order := &Order{id: "A-1042", customer: &Customer{name: "Ania", loyalty: &LoyaltyAccount{points: 250}}, total: 4590}
	if err := order.RedeemPoints(200); err != nil { // Checkout talks only to its friend: the order
		fmt.Println(err)
	}
	fmt.Println(order) // A-1042: 25.90 zł, Ania has 50 points left
}
loyalty.py
class LoyaltyAccount:
    GROSZE_PER_POINT = 10

    def __init__(self, points: int) -> None:
        self._points = points

    @property
    def balance(self) -> int:
        return self._points

    def redeem(self, points: int, max_discount: int) -> int:
        """Tell the account to redeem – don't read its balance and do the maths outside."""
        discount = points * self.GROSZE_PER_POINT
        if points > self._points:
            raise ValueError("Not enough points")
        if discount > max_discount:
            raise ValueError("Discount larger than the order")
        self._points -= points
        return discount


class Customer:
    def __init__(self, name: str, loyalty: LoyaltyAccount) -> None:
        self._name = name
        self._loyalty = loyalty

    def redeem_points(self, points: int, max_discount: int) -> int:
        return self._loyalty.redeem(points, max_discount)

    def __str__(self) -> str:
        return f"{self._name} has {self._loyalty.balance} points left"


class Order:
    def __init__(self, order_id: str, customer: Customer, total: int) -> None:
        self._id = order_id
        self._customer = customer
        self._total = total  # grosze

    def redeem_points(self, points: int) -> None:
        self._total -= self._customer.redeem_points(points, self._total)

    def __str__(self) -> str:
        return f"{self._id}: {self._total // 100}.{self._total % 100:02d} zł, {self._customer}"


order = Order("A-1042", Customer("Ania", LoyaltyAccount(250)), 4590)
order.redeem_points(200)  # Checkout talks only to its friend: the order
print(order)  # A-1042: 25.90 zł, Ania has 50 points left

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Exceptions: fluent interfaces, DTOs and queries
  • Encapsulation and coupling metrics
  • When to use it and when not to
  • In practice
  • Related topics
  • Test yourself

Create a free account · Sign in