English

Artykuł · Prawo Demeter · Fasada

Prawo Demeter: rozmawiaj tylko z przyjaciółmi

Prawo Demeter (zasada minimalnej wiedzy) na przykładzie wymiany punktów lojalnościowych w pierogarni Haliny: łańcuchy wywołań kontra „mów, nie pytaj”, wyjątki dla interfejsów płynnych i DTO, kod w C#, TypeScript, Javie, Go i Pythonie oraz związek z hermetyzacją i metrykami sprzężeń.

Autor · · 15 min czytania

Klient pierogarni Haliny płaci za zamówienie punktami z programu lojalnościowego: 200 punktów to 20 zł rabatu. Kod kasy zna przy tym całe drzewo genealogiczne zamówienia: order.getCustomer().getLoyaltyAccount().getBalance().getPoints(). Prawo Demeter (ang. Law of Demeter), nazywane też zasadą minimalnej wiedzy (ang. Principle of Least Knowledge), mówi: obiekt rozmawia tylko ze swoimi bezpośrednimi współpracownikami, a nie z ich wnętrzem.

1987
Northeastern University – Ian Holland formułuje zasadę w projekcie Demeter
5 → 1
klasy znane kasie – przed refaktoryzacją i po niej
4
rodzaje „przyjaciół” metody – jej obiekt, parametry, utworzone obiekty i pola

Skąd się wzięło prawo Demeter

Zasadę sformułował w 1987 roku Ian Holland w projekcie Demeter na Northeastern University, prowadzonym przez Karla Lieberherra. Nazwa pochodzi od projektu, a projekt – od greckiej bogini rolnictwa: chodziło o oprogramowanie, które „rośnie” stopniowo. Rok później Lieberherr, Holland i Riel opisali zasadę na konferencji OOPSLA. Potoczna wersja brzmi: rozmawiaj tylko z przyjaciółmi, nie rozmawiaj z nieznajomymi.

Formalnie metoda m obiektu O może wywoływać metody tylko następujących „przyjaciół”:

PrzyjacielPrzykład w Order.redeemPoints
sam obiekt Othis.applyDiscount(...)
parametry metody mpoints przekazane przez kasę
obiekty utworzone w mnew Discount(...)
pola (komponenty) obiektu Othis.customer.redeemPoints(...)

Oryginalne sformułowanie dopuszcza też zmienne globalne dostępne w zasięgu metody – dziś traktujemy je raczej jako problem niż przyjaciela. Nie wolno natomiast wołać metod obiektów zwróconych przez te wywołania: this.customer.getLoyaltyAccount().redeem(...) rozmawia już z nieznajomym.

Problem: kasa, która wie za dużo

Pierwsza wersja wymiany punktów powstała w kasie (ang. checkout), bo „tam są potrzebne”:

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);
}

Takie łańcuchy nazywa się train wreck – wagony kropek sprzęgnięte jeden za drugim. Martin Fowler w Refactoring opisuje je jako zapach kodu Message Chains. Co jest z nimi nie tak?

  • Kasa zna pięć klas – zamówienie, klienta, konto lojalnościowe, saldo i kwotę – oraz to, jak są ze sobą połączone. Każda zmiana tej struktury psuje kod. Ten sam łańcuch był też w API aplikacji mobilnej i w panelu administratora, więc gdy punkty przeniesiono do osobnego portfela klienta, poprawki objęły trzy miejsca.
  • Reguła programu lojalnościowego wyciekła. Przelicznik „1 punkt = 10 groszy” mieszka w kasie, a pewnie też w aplikacji mobilnej (zob. DRY).
  • Najpierw pytaj, potem działaj. Kod odczytuje saldo, sam decyduje i zapisuje wynik przez settery. Niezmiennika „saldo nie spada poniżej zera” pilnuje wywołujący, a nie obiekt, który to saldo ma.
  • Atrapy zwracające atrapy. Żeby przetestować kasę, trzeba zbudować atrapę zamówienia, która zwraca atrapę klienta, która zwraca atrapę konta…
Diagram: Kogo zna kasa: przed refaktoryzacją i po niej

Rozwiązanie: mów, nie pytaj

Zasadę Tell, Don't Ask („mów, nie pytaj”) spopularyzowali Andy Hunt i Dave Thomas w artykule The Art of Enbugging (2003): zamiast pytać obiekt o stan i decydować za niego, powiedz mu, co ma zrobić. Każdy obiekt wykonuje swoją część pracy i rozmawia tylko z sąsiadem: zamówienie zna swoją kwotę i ogranicza rabat, klient przekazuje prośbę swojemu kontu, a konto sprawdza saldo i przelicza punkty.

Diagram: Wymiana punktów: każdy rozmawia tylko z sąsiadem

Mów, nie pytaj – wymiana punktów lojalnościowych

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

Dalsza część artykułu dla zalogowanych

Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:

  • Wyjątki: interfejsy płynne, DTO i zapytania
  • Hermetyzacja i metryki sprzężeń
  • Kiedy stosować, a kiedy nie
  • W praktyce
  • Powiązania
  • Sprawdź się

Załóż darmowe konto · Zaloguj się