DRY: one piece of knowledge, one place – and when duplication is cheaper
The DRY principle through the order rules of Halina's pierogi place: knowledge duplication vs code duplication, the Rule of Three, Sandi Metz's wrong abstraction, a single source of truth for validation, schemas and configuration in C#, TypeScript, Java, Go and Python, plus WET and AHA.
The minimum order value in Halina's pierogi place went up from 40 to 45 zł in March. Someone changed it in the API, but the shop's checkout form and the abandoned-cart e-mail still say "40 zł" – customers get an error they don't understand, and Halina gets phone calls from annoyed regulars. DRY (Don't Repeat Yourself) is not about similar lines of code but about knowledge: every rule should have one authoritative place in the system.
- 1999
- "The Pragmatic Programmer" – Andy Hunt and Dave Thomas state the DRY principle
- 3
- the Rule of Three – refactor on the third repetition (Don Roberts)
- 45 ≠ 40
- the minimum in the API and in the form – one rule, two truths
Where DRY comes from
Andy Hunt and Dave Thomas stated the principle in The Pragmatic Programmer (1999): every piece of knowledge must have a single, unambiguous, authoritative representation within a system. The key word is knowledge. Duplication is not only a copied function, but also a comment that repeats the code, hand-written API docs living next to the controllers, or the same rule written once in SQL and once in the application. The authors have stressed many times that DRY is often misread as "never write two similar lines".
Knowledge duplication vs code duplication
The simplest test: when the rule changes, do all the copies have to change? If yes, it is the same knowledge. If the copies change for different reasons and at different times, it is just similar code.
| Knowledge duplication | Coincidentally similar code | |
|---|---|---|
| Example | the 45 zł minimum in the API, the form and the e-mail | a 200-character limit for courier notes and for pierogi reviews |
| Change test | changing the rule means changing every copy | each copy changes for a different reason |
| What to do | one source of truth | keep them apart and name each constant separately |
The courier-note limit comes from the screen of the courier app; the review limit comes from moderation rules. When marketing asks for longer reviews, a shared MAX_TEXT = 200 constant silently changes the courier app too. It also works the other way round: the same knowledge can look completely different – if (total < 45) in C# and CHECK (total >= 45) in SQL share not a single character, and they are still duplicates.
The problem: three places, three truths
This is the minimum-order rule after the March change – only one of the three places was updated:
// 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ł!';Each of these lines is correct and readable on its own. The problem is that the business rule "what is the minimum" has three owners, and none of them knows about the others. The mobile app, which lives in a separate repository, holds a fourth copy.
The solution: a single source of truth
The order rules move into one module. The API validates against them, error messages are built from the same constants, and the checkout form, the mobile app and the e-mail templates download the rules from GET /api/order-rules instead of hard-coding numbers.
A single source of order rules
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())The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- DRY across layers
- The Rule of Three
- The wrong abstraction
- WET, AHA and DAMP
- When to use it and when not to
- In practice
- Related topics
- Test yourself