
DRY
Don’t Repeat Yourself
“Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.” – Andy Hunt & Dave Thomas
Duplication is the root of all evil in software.
When to use
When you find yourself copying and pasting code, or when you realized you need to make the same logical change in two different places.
Why it matters
- Maintainability: Fix a bug once, and it’s fixed everywhere.
- Consistency: Prevents business logic from drifting apart in different parts of the application.
Signs of Violation
- Copy-pasted code blocks.
- Multiple classes representing the same concept (e.g.,
UserDTO,UserEntity,UserModelthat are identical). - Magic numbers repeated throughout the code.
Explanation
Problem
If logic is duplicated, it eventually diverges. One copy gets updated, the other doesn’t. This leads to subtle bugs where feature X works in the App but not in the API.
Solution
Abstraction. Extract the common logic into a function, class, or constant.
Real world analogy
Government forms. You shouldn’t have to fill out your Name, Address, and birthdate on 5 different pages of the same application. You fill it once (Single Source of Truth), and it’s referenced everywhere else.
Pros and Cons
| Pros | Cons |
|---|---|
Comparison
- WET (Write Everything Twice): The opposite of DRY. Sometimes acceptable in tests or decoupling phases.
- Rule of Three: Wait until you see duplication 3 times before you abstract it.
Code example
Typescript
Bad (Violation)
Good (Adherence)
PHP
Bad (Violation)
Good (Adherence)