How to remove duplicate code with the DRY principle
DRY principle, code duplication types, extracting common logic, when not to DRY, rule of three, abstraction traps
DRY: Don't Repeat Yourself (But Know the Limits)
DRY — Don't Repeat Yourself — means every piece of knowledge should have a single authoritative representation. When you change a rule, you change it in one place and it updates everywhere. Duplication means changing it in every copy and missing at least one.
// Duplication — same validation in three places
function createUser(email) {
if (!email.includes('@')) throw new Error('Invalid email');
...
}
function updateEmail(email) {
if (!email.includes('@')) throw new Error('Invalid email');
...
}
function inviteUser(email) {
if (!email.includes('@')) throw new Error('Invalid email');
...
}Extract the duplicated logic once:
function assertValidEmail(email) {
if (!email.includes('@')) throw new Error('Invalid email');
}
function createUser(email) { assertValidEmail(email); ... }
function updateEmail(email) { assertValidEmail(email); ... }
function inviteUser(email) { assertValidEmail(email); ... }Now email validation is defined once. Any change to the rule changes all three callers automatically.
The rule of three: don't extract on the first duplication. Wait until you see the same code three times — then extract. Two occurrences might be coincidence; three is a pattern.
The abstraction trap: DRY can go wrong when two pieces of code look the same but represent different concepts. Forcing them into one function creates a coupling that makes both harder to change. Ask: are these two uses of the same rule, or two different rules that currently happen to look alike?
