Polski

Article · YAGNI · KISS

YAGNI: don't build ahead – what a feature nobody ordered really costs

The YAGNI principle through the online shop of Halina's pierogi place: its Extreme Programming origins, the four costs of building ahead, YAGNI vs extension points and feature flags, and removing premature abstraction from payment code in C#, TypeScript, Java, Go and Python.

By · · 18 min read

When Halina's pierogi place went online, the developer prepared – "just in case" – support for euros and Czech korunas, a payment-operator factory, and multi-tenancy for a future franchise. A year later the shop has taken zero orders in euros, there is one payment operator, and still just one restaurant. The code, however, stayed, and every change to the cart has to pass through layers that serve no purpose. YAGNI (You Aren't Gonna Need It) is the principle of building features when you need them, not when you foresee them.

1999
"Extreme Programming Explained" – Kent Beck describes XP and simple design
4
costs of building ahead – build, delay, carry and repair – according to Martin Fowler
0
orders in euros after a year – yet currency handling touches every cart change

Where YAGNI comes from

YAGNI is one of the mantras of Extreme Programming (XP) – a method that, instead of designing everything up front, delivers small increments and keeps improving the design.

  1. 1996 The C3 project at Chrysler – Kent Beck takes over the project and, with his team (including Ron Jeffries), shapes the practices that become Extreme Programming.
  2. 1999 "Extreme Programming Explained" – Kent Beck describes XP; simple design is one of its practices.
  3. 2001 The Agile Manifesto – Among its principles: simplicity – the art of maximizing the amount of work not done – is essential.
  4. 2015 Martin Fowler, "Yagni" – Lays out the four costs of building a feature ahead and the limits of the principle.

Always implement things when you actually need them, never when you just foresee that you need them.

— Ron Jeffries, co-founder of Extreme Programming

The problem: a shop built for a future that never came

Here is the payment code after a year in production. Every extension point was created on day one, and none of them has been used:

Before – payments with extension points built ahead

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")))

The rest of this article is for members

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

  • What building ahead costs
  • The solution: remove the speculative generality
  • YAGNI vs extension points
  • Feature flags
  • Examples of premature abstraction
  • When to use it and when not to
  • In practice
  • Related topics
  • Test yourself

Create a free account · Sign in