DRY (Don't Repeat Yourself)
Every piece of knowledge should have a single, unambiguous representation.
Tiny Summary
DRY: "Don't Repeat Yourself." Every piece of logic should exist in exactly one place. Duplication is the enemy of maintainability.
The Principle
Don't: Repeat validation logic (copy-paste same if (user.age < 18) check multiple times)
Do: Extract to function validateAge(user) and call it. Single source of truth.
Why DRY Matters
Single source of truth: Change once → Updates everywhere. No risk of forgetting copy-pasted code.
Bug fixes: Fix once, fixed everywhere. Duplicated code → fix in N places (easy to miss).
Easier refactoring: Change business logic once, all callers benefit.
Common Violations
Copy-paste code: Payment logic copied 5 times. Bug fix? Update all 5 (you'll miss one).
Hardcoded values: Port 8080 in 20 files. Changing port → search/replace nightmare. Use constant: PORT = 8080.
Database queries: Same SQL in 10 services. Schema change → update 10 places. Extract to repository pattern.
When to Violate DRY
Coincidental duplication: Two things look similar now but will diverge. Premature abstraction worse than duplication. Wait for third occurrence.
Different domains: User validation in auth vs billing may look similar but have different requirements.
Performance: Sometimes duplication is faster. Hot paths may benefit from inlining.
The Rule of Three
First time: Write code. Second time: Grumble, but duplicate. Third time: Refactor into shared function. Don't abstract too early—wait for pattern to emerge.
Key Insights
Duplication creates maintenance burden, but premature abstraction is also bad. Balance: DRY when pattern is clear, WET when uncertain. "Every piece of knowledge should have a single source." DRY applies to logic, not just code (configs, docs, tests). WET ("Write Everything Twice") is the opposite—a maintenance nightmare.