English

Artykuł · YAGNI · KISS

YAGNI: nie buduj na zapas – ile kosztuje funkcja, której nikt nie zamówił

Zasada YAGNI na przykładzie sklepu internetowego pierogarni Haliny: pochodzenie z Extreme Programming, cztery koszty funkcji budowanej na zapas, YAGNI a punkty rozszerzeń i flagi funkcji oraz usuwanie przedwczesnej abstrakcji z kodu płatności w C#, TypeScript, Javie, Go i Pythonie.

Autor · · 16 min czytania

Gdy pierogarnia Haliny wchodziła do internetu, programista „na wszelki wypadek” przygotował obsługę euro i koron, fabrykę operatorów płatności i wielodostępność pod przyszłą franczyzę. Po roku sklep przyjął zero zamówień w euro, operator płatności jest jeden, a lokal – nadal jeden. Kod jednak został i każdą zmianę w koszyku trzeba przeprowadzać przez warstwy, które niczemu nie służą. YAGNI (ang. You Aren't Gonna Need It – „nie będziesz tego potrzebować”) to zasada, by budować funkcje wtedy, gdy są potrzebne, a nie wtedy, gdy się je przewiduje.

1999
„Extreme Programming Explained” – Kent Beck opisuje XP i prosty projekt
4
koszty funkcji na zapas – budowa, opóźnienie, utrzymanie i naprawa – według Martina Fowlera
0
zamówień w euro po roku – a obsługa walut dotyka każdej zmiany w koszyku

Skąd się wzięło YAGNI

YAGNI to jedna z mantr Extreme Programming (XP) – metodyki, która zamiast projektować wszystko z góry, każe dostarczać małe przyrosty i ciągle poprawiać projekt.

  1. 1996 Projekt C3 w Chryslerze – Kent Beck obejmuje projekt i razem z zespołem (m.in. Ronem Jeffriesem) układa praktyki, które staną się Extreme Programming.
  2. 1999 „Extreme Programming Explained” – Kent Beck opisuje XP; prosty projekt (ang. *simple design*) jest jedną z jego praktyk.
  3. 2001 Manifest Agile – Wśród zasad: prostota – sztuka maksymalizacji ilości pracy, której nie trzeba wykonać – jest kluczowa.
  4. 2015 Martin Fowler, „Yagni” – Rozpisanie czterech kosztów funkcji budowanej na zapas i granic stosowania zasady.

Zawsze implementuj rzeczy wtedy, gdy rzeczywiście ich potrzebujesz, nigdy wtedy, gdy tylko przewidujesz, że będą potrzebne.

— Ron Jeffries, współtwórca Extreme Programming

Problem: sklep zbudowany pod przyszłość, która nie przyszła

Kod płatności po roku działania sklepu. Wszystkie punkty rozszerzeń powstały pierwszego dnia, a żaden nie został użyty:

Przed – płatności z punktami rozszerzeń na zapas

Payments.cs
// Before: built "for the future" – one operator, one currency, three extension points.
var factory = new PaymentGatewayFactory(new PlnOnlyRates());
var gateway = factory.Create(GatewayKind.CardOperator);
Console.WriteLine(gateway.Charge("A-1042", new Money(45.90m, "PLN")));

public sealed record Money(decimal Amount, string Currency);

public interface IExchangeRates { decimal ToPln(string currency); }

public sealed class PlnOnlyRates : IExchangeRates
{
    // The only currency we have seen in two years.
    public decimal ToPln(string currency) =>
        currency == "PLN" ? 1m : throw new NotSupportedException($"No rates for {currency} yet");
}

public enum GatewayKind { CardOperator } // "we will add more providers later"

public interface IPaymentGateway { string Charge(string orderId, Money amount); }

public sealed class CardOperatorGateway(IExchangeRates rates) : IPaymentGateway
{
    public string Charge(string orderId, Money amount)
    {
        var pln = amount.Amount * rates.ToPln(amount.Currency);
        return $"Charged {pln} PLN for order {orderId}"; // the real HTTP call goes here
    }
}

public sealed class PaymentGatewayFactory(IExchangeRates rates)
{
    public IPaymentGateway Create(GatewayKind kind) => kind switch
    {
        GatewayKind.CardOperator => new CardOperatorGateway(rates),
        _ => throw new NotSupportedException($"Unknown gateway {kind}"),
    };
}
payments.ts
// Before: built "for the future" – one operator, one currency, three extension points.
interface Money { amount: number; currency: string } // amount in minor units
interface ExchangeRates { toPln(currency: string): number }

const plnOnlyRates: ExchangeRates = {
  toPln(currency) {
    if (currency !== 'PLN') throw new Error(`No rates for ${currency} yet`); // the only currency in two years
    return 1;
  },
};

type GatewayKind = 'card-operator'; // "we will add more providers later"

interface PaymentGateway { charge(orderId: string, amount: Money): string }

class CardOperatorGateway implements PaymentGateway {
  constructor(private readonly rates: ExchangeRates) {}
  charge(orderId: string, amount: Money): string {
    const grosze = amount.amount * this.rates.toPln(amount.currency);
    return `Charged ${(grosze / 100).toFixed(2)} PLN for order ${orderId}`; // the real HTTP call goes here
  }
}

class PaymentGatewayFactory {
  constructor(private readonly rates: ExchangeRates) {}
  create(kind: GatewayKind): PaymentGateway {
    switch (kind) {
      case 'card-operator':
        return new CardOperatorGateway(this.rates);
      default:
        throw new Error(`Unknown gateway ${String(kind)}`);
    }
  }
}

const gateway = new PaymentGatewayFactory(plnOnlyRates).create('card-operator');
console.log(gateway.charge('A-1042', { amount: 4_590, currency: 'PLN' }));
Payments.java
import java.math.BigDecimal;

// Before: built "for the future" – one operator, one currency, three extension points.
public class Payments {
    public static void main(String[] args) {
        var gateway = new PaymentGatewayFactory(new PlnOnlyRates()).create(GatewayKind.CARD_OPERATOR);
        System.out.println(gateway.charge("A-1042", new Money(new BigDecimal("45.90"), "PLN")));
    }
}

record Money(BigDecimal amount, String currency) {}

interface ExchangeRates { BigDecimal toPln(String currency); }

class PlnOnlyRates implements ExchangeRates {
    // The only currency we have seen in two years.
    public BigDecimal toPln(String currency) {
        if (!currency.equals("PLN")) throw new UnsupportedOperationException("No rates for " + currency + " yet");
        return BigDecimal.ONE;
    }
}

enum GatewayKind { CARD_OPERATOR } // "we will add more providers later"

interface PaymentGateway { String charge(String orderId, Money amount); }

record CardOperatorGateway(ExchangeRates rates) implements PaymentGateway {
    public String charge(String orderId, Money amount) {
        var pln = amount.amount().multiply(rates.toPln(amount.currency()));
        return "Charged " + pln + " PLN for order " + orderId; // the real HTTP call goes here
    }
}

record PaymentGatewayFactory(ExchangeRates rates) {
    PaymentGateway create(GatewayKind kind) {
        return switch (kind) {
            case CARD_OPERATOR -> new CardOperatorGateway(rates);
        };
    }
}
payments.go
package main

import "fmt"

// Before: built "for the future" – one operator, one currency, three extension points.
type Money struct {
	Amount   int64 // minor units
	Currency string
}

type ExchangeRates interface{ ToPLN(currency string) (int64, error) }

type PLNOnlyRates struct{}

// The only currency we have seen in two years.
func (PLNOnlyRates) ToPLN(currency string) (int64, error) {
	if currency != "PLN" {
		return 0, fmt.Errorf("no rates for %s yet", currency)
	}
	return 1, nil
}

type GatewayKind int

const CardOperator GatewayKind = iota // "we will add more providers later"

type PaymentGateway interface {
	Charge(orderID string, amount Money) (string, error)
}

type CardOperatorGateway struct{ rates ExchangeRates }

func (g CardOperatorGateway) Charge(orderID string, amount Money) (string, error) {
	rate, err := g.rates.ToPLN(amount.Currency)
	if err != nil {
		return "", err
	}
	grosze := amount.Amount * rate // the real HTTP call goes here
	return fmt.Sprintf("Charged %d.%02d PLN for order %s", grosze/100, grosze%100, orderID), nil
}

func NewGateway(kind GatewayKind, rates ExchangeRates) (PaymentGateway, error) {
	switch kind {
	case CardOperator:
		return CardOperatorGateway{rates: rates}, nil
	default:
		return nil, fmt.Errorf("unknown gateway %d", kind)
	}
}

func main() {
	gateway, _ := NewGateway(CardOperator, PLNOnlyRates{})
	fmt.Println(gateway.Charge("A-1042", Money{Amount: 4590, Currency: "PLN"}))
}
payments.py
from dataclasses import dataclass
from decimal import Decimal
from enum import Enum
from typing import Protocol


# Before: built "for the future" – one operator, one currency, three extension points.
@dataclass(frozen=True)
class Money:
    amount: Decimal
    currency: str


class ExchangeRates(Protocol):
    def to_pln(self, currency: str) -> Decimal: ...


class PlnOnlyRates:
    def to_pln(self, currency: str) -> Decimal:
        if currency != "PLN":  # the only currency we have seen in two years
            raise NotImplementedError(f"No rates for {currency} yet")
        return Decimal("1")


class GatewayKind(Enum):
    CARD_OPERATOR = "card-operator"  # "we will add more providers later"


class PaymentGateway(Protocol):
    def charge(self, order_id: str, amount: Money) -> str: ...


class CardOperatorGateway:
    def __init__(self, rates: ExchangeRates) -> None:
        self._rates = rates

    def charge(self, order_id: str, amount: Money) -> str:
        pln = amount.amount * self._rates.to_pln(amount.currency)
        return f"Charged {pln} PLN for order {order_id}"  # the real HTTP call goes here


class PaymentGatewayFactory:
    def __init__(self, rates: ExchangeRates) -> None:
        self._rates = rates

    def create(self, kind: GatewayKind) -> PaymentGateway:
        match kind:
            case GatewayKind.CARD_OPERATOR:
                return CardOperatorGateway(self._rates)
        raise ValueError(f"Unknown gateway {kind}")


gateway = PaymentGatewayFactory(PlnOnlyRates()).create(GatewayKind.CARD_OPERATOR)
print(gateway.charge("A-1042", Money(Decimal("45.90"), "PLN")))

Dalsza część artykułu dla zalogowanych

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

  • Ile kosztuje funkcja na zapas
  • Rozwiązanie: usuń spekulatywną ogólność
  • YAGNI a punkty rozszerzeń
  • Flagi funkcji
  • Przykłady przedwczesnej abstrakcji
  • Kiedy stosować, a kiedy nie
  • W praktyce
  • Powiązania
  • Sprawdź się

Załóż darmowe konto · Zaloguj się