DRY: jedna wiedza, jedno miejsce – i kiedy duplikacja jest tańsza
Zasada DRY na przykładzie reguł zamówień w pierogarni Haliny: duplikacja wiedzy a duplikacja kodu, reguła trzech, zła abstrakcja według Sandi Metz, jedno źródło prawdy dla walidacji, schematów i konfiguracji w C#, TypeScript, Javie, Go i Pythonie oraz WET i AHA.
Minimalna wartość zamówienia w pierogarni Haliny wzrosła w marcu z 40 do 45 zł. Ktoś zmienił ją w API, ale formularz w sklepie i e-mail o porzuconym koszyku dalej mówią „40 zł” – klienci dostają błąd, którego nie rozumieją, a Halina telefony od zdenerwowanych stałych gości. DRY (ang. Don't Repeat Yourself – „nie powtarzaj się”) nie dotyczy podobnych linijek kodu, tylko wiedzy: każda reguła powinna mieć w systemie jedno, autorytatywne miejsce.
- 1999
- „The Pragmatic Programmer” – Andy Hunt i Dave Thomas formułują zasadę DRY
- 3
- reguła trzech – refaktoryzuj przy trzecim powtórzeniu (Don Roberts)
- 45 ≠ 40
- minimum w API i w formularzu – jedna reguła, dwie prawdy
Skąd się wzięło DRY
Zasadę sformułowali Andy Hunt i Dave Thomas w książce The Pragmatic Programmer (1999): każdy fragment wiedzy musi mieć w systemie jedną, jednoznaczną i autorytatywną reprezentację. Słowo kluczowe to wiedza. Duplikacją jest nie tylko skopiowana funkcja, ale też komentarz, który powtarza kod, ręcznie pisana dokumentacja API obok kontrolerów, czy ta sama reguła zapisana raz w SQL, a raz w aplikacji. Autorzy wielokrotnie podkreślali, że DRY bywa źle rozumiane jako „nigdy nie pisz dwa razy podobnych linijek”.
Duplikacja wiedzy a duplikacja kodu
Najprostszy test: gdy reguła się zmieni, czy trzeba zmienić wszystkie kopie? Jeśli tak – to ta sama wiedza. Jeśli kopie zmieniają się z różnych powodów i w różnym czasie, to tylko podobny kod.
| Duplikacja wiedzy | Przypadkowa zbieżność kodu | |
|---|---|---|
| Przykład | minimum 45 zł w API, formularzu i e-mailu | limit 200 znaków dla uwag dla kuriera i dla opinii o pierogach |
| Test zmiany | zmiana reguły wymaga zmiany każdej kopii | każda kopia zmienia się z innego powodu |
| Co robić | jedno źródło prawdy | zostawić osobno i nazwać każdą stałą osobno |
Limit uwag dla kuriera wynika z ekranu w jego aplikacji, a limit opinii – z zasad moderacji. Gdy marketing poprosi o dłuższe opinie, wspólna stała MAX_TEXT = 200 po cichu zmieni też aplikację kuriera. Działa to w obie strony: ta sama wiedza może wyglądać zupełnie inaczej – if (total < 45) w C# i CHECK (total >= 45) w SQL nie mają ani jednego wspólnego znaku, a to wciąż duplikat.
Problem: trzy miejsca, trzy prawdy
Tak wygląda reguła minimalnego zamówienia po marcowej zmianie – poprawiono tylko jedno z trzech miejsc:
// web/checkout-form.ts
if (cart.total < 40) showError('Minimum order is 40 zł');
// api/orders.controller.ts – raised to 45 zł in March
if (dto.total < 45) throw new BadRequestException('Minimum order is 45 zł');
// emails/abandoned-cart.ts
const hint = 'Add one more portion – the minimum order is only 40 zł!';Każda z tych linijek z osobna jest poprawna i czytelna. Problem w tym, że reguła biznesowa „ile minimum” ma trzech właścicieli, a żaden z nich nie wie o pozostałych. Aplikacja mobilna, której kod jest w osobnym repozytorium, ma czwartą kopię.
Rozwiązanie: jedno źródło prawdy
Reguły zamówień trafiają do jednego modułu. API waliduje na ich podstawie, komunikaty błędów są budowane z tych samych stałych, a formularz, aplikacja mobilna i szablony e-maili pobierają reguły z endpointu GET /api/order-rules zamiast wpisywać liczby na sztywno.
Jedno źródło reguł zamówienia
using System.Text.Json;
using System.Text.RegularExpressions;
var draft = new OrderDraft(Total: 38m, Portions: 22, Phone: "600-100-200");
foreach (var error in OrderRules.Validate(draft)) Console.WriteLine(error);
Console.WriteLine(JsonSerializer.Serialize(OrderRules.Public)); // served at GET /api/order-rules
public sealed record OrderDraft(decimal Total, int Portions, string Phone);
// The single, authoritative place for order rules.
public static partial class OrderRules
{
public const decimal MinTotal = 45m;
public const int MaxPortions = 20;
public const string PhonePattern = @"^\d{9}$";
// What the web form, the mobile app and e-mail templates read instead of hard-coding numbers.
public static readonly object Public = new { minTotal = MinTotal, maxPortions = MaxPortions, phonePattern = PhonePattern };
public static IEnumerable<string> Validate(OrderDraft order)
{
if (order.Total < MinTotal) yield return $"Minimum order is {MinTotal} zł";
if (order.Portions > MaxPortions) yield return $"At most {MaxPortions} portions per order";
if (!Phone().IsMatch(order.Phone)) yield return "Phone number must have 9 digits";
}
[GeneratedRegex(PhonePattern)]
private static partial Regex Phone();
}// The single, authoritative place for order rules.
export const ORDER_RULES = {
minTotal: 4_500, // grosze
maxPortions: 20,
phonePattern: '^\\d{9}$',
} as const;
export interface OrderDraft { total: number; portions: number; phone: string }
export function validateOrder(order: OrderDraft): string[] {
const errors: string[] = [];
if (order.total < ORDER_RULES.minTotal) errors.push(`Minimum order is ${ORDER_RULES.minTotal / 100} zł`);
if (order.portions > ORDER_RULES.maxPortions) errors.push(`At most ${ORDER_RULES.maxPortions} portions per order`);
if (!new RegExp(ORDER_RULES.phonePattern).test(order.phone)) errors.push('Phone number must have 9 digits');
return errors;
}
// Served at GET /api/order-rules – the web form, the mobile app and e-mail templates
// read it instead of hard-coding numbers.
export const publicOrderRules = (): string => JSON.stringify(ORDER_RULES);
console.log(validateOrder({ total: 3_800, portions: 22, phone: '600-100-200' }));
console.log(publicOrderRules());import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
// The single, authoritative place for order rules.
public final class OrderRules {
public static final BigDecimal MIN_TOTAL = new BigDecimal("45");
public static final int MAX_PORTIONS = 20;
public static final String PHONE_PATTERN = "^\\d{9}$";
private static final Pattern PHONE = Pattern.compile(PHONE_PATTERN);
private OrderRules() {}
public record OrderDraft(BigDecimal total, int portions, String phone) {}
public static List<String> validate(OrderDraft order) {
var errors = new ArrayList<String>();
if (order.total().compareTo(MIN_TOTAL) < 0) errors.add("Minimum order is " + MIN_TOTAL + " zł");
if (order.portions() > MAX_PORTIONS) errors.add("At most " + MAX_PORTIONS + " portions per order");
if (!PHONE.matcher(order.phone()).matches()) errors.add("Phone number must have 9 digits");
return errors;
}
// Served at GET /api/order-rules (e.g. a Spring @GetMapping that returns this map as JSON).
public static Map<String, Object> publicRules() {
var rules = new LinkedHashMap<String, Object>();
rules.put("minTotal", MIN_TOTAL);
rules.put("maxPortions", MAX_PORTIONS);
rules.put("phonePattern", PHONE_PATTERN);
return rules;
}
public static void main(String[] args) {
System.out.println(validate(new OrderDraft(new BigDecimal("38"), 22, "600-100-200")));
System.out.println(publicRules());
}
}package main
import (
"encoding/json"
"fmt"
"regexp"
)
// OrderRules is the single, authoritative place for order rules.
// The JSON tags let us serve it as-is at GET /api/order-rules.
type OrderRules struct {
MinTotal int64 `json:"minTotal"` // grosze
MaxPortions int `json:"maxPortions"`
PhonePattern string `json:"phonePattern"`
}
var Rules = OrderRules{MinTotal: 4500, MaxPortions: 20, PhonePattern: `^\d{9}$`}
var phoneRe = regexp.MustCompile(Rules.PhonePattern)
type OrderDraft struct {
Total int64
Portions int
Phone string
}
func ValidateOrder(o OrderDraft) []string {
var errs []string
if o.Total < Rules.MinTotal {
errs = append(errs, fmt.Sprintf("Minimum order is %d zł", Rules.MinTotal/100))
}
if o.Portions > Rules.MaxPortions {
errs = append(errs, fmt.Sprintf("At most %d portions per order", Rules.MaxPortions))
}
if !phoneRe.MatchString(o.Phone) {
errs = append(errs, "Phone number must have 9 digits")
}
return errs
}
func main() {
fmt.Println(ValidateOrder(OrderDraft{Total: 3800, Portions: 22, Phone: "600-100-200"}))
public, _ := json.Marshal(Rules) // what the web form and the mobile app download
fmt.Println(string(public))
}import json
import re
from dataclasses import asdict, dataclass
from decimal import Decimal
@dataclass(frozen=True)
class OrderRules:
"""The single, authoritative place for order rules."""
min_total: Decimal = Decimal("45")
max_portions: int = 20
phone_pattern: str = r"^\d{9}$"
RULES = OrderRules()
@dataclass(frozen=True)
class OrderDraft:
total: Decimal
portions: int
phone: str
def validate_order(order: OrderDraft, rules: OrderRules = RULES) -> list[str]:
errors = []
if order.total < rules.min_total:
errors.append(f"Minimum order is {rules.min_total} zł")
if order.portions > rules.max_portions:
errors.append(f"At most {rules.max_portions} portions per order")
if not re.fullmatch(rules.phone_pattern, order.phone):
errors.append("Phone number must have 9 digits")
return errors
def public_rules(rules: OrderRules = RULES) -> str:
"""Served at GET /api/order-rules for the web form, the mobile app and e-mail templates."""
return json.dumps(asdict(rules), default=str)
print(validate_order(OrderDraft(Decimal("38"), 22, "600-100-200")))
print(public_rules())Dalsza część artykułu dla zalogowanych
Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:
- DRY między warstwami
- Reguła trzech
- Zła abstrakcja
- WET, AHA i DAMP
- Kiedy stosować, a kiedy nie
- W praktyce
- Powiązania
- Sprawdź się