Skip to content

What does it mean when people say 'don't repeat yourself' in code?

DRY comes up in every code review discussion. What does it actually mean in practice, and is it possible to take it too far?
10
1 answers400 views

1 Answer

Accepted answer

RNRahul N.2.1K XP1mo ago
DRY means each piece of knowledge in your system should have one authoritative home, so a change happens in one place instead of five. It is about knowledge duplication, not about text that happens to look similar — and that distinction is exactly where people take it too far. The classic good case: you calculate a discount in four different files. A rule change means finding all four, and you will miss one, and the bug will be subtle. Extracting one `calculateDiscount()` function means the rule lives in one place with one definition. Same for a magic number repeated everywhere, a validation rule copy-pasted across forms, or a database query duplicated in three routes. How to spot it: when you change something and find yourself making 'the same change' in multiple places, that's a DRY violation, and the pain you just felt is the signal. Duplication is cheap to create and expensive to maintain, and the cost shows up months later. Now the overcorrection, which is genuinely as harmful. Two pieces of code that look identical today but represent *different* rules are not duplication — they're a coincidence. If you merge them, the day one rule changes you'll add a flag parameter, then another, and end up with a function full of `if (isCheckout)` branches that nobody can safely modify. That's a worse outcome than the original copy-paste. The practical heuristics: 1. Wait for the third occurrence before abstracting. Two similar things might be coincidence; three is usually a pattern. Premature abstraction based on one similarity is a common and costly mistake. 2. Ask 'would these always change together?' If yes, it's real duplication — unify it. If they'd change for different reasons, leave them separate. 3. Prefer a little duplication over the wrong abstraction. Duplicated code is easy to see and easy to fix later. A tangled shared function with six flags is hard to untangle and radiates bugs into everything that calls it. 4. Watch for the flag parameter smell. When your shared function starts taking booleans that switch behaviour, you probably merged two things that should be apart. The balanced version most experienced developers land on: aggressively de-duplicate genuine business rules, constants and data-access logic; be relaxed about superficially similar code in unrelated features. DRY is a tool for making change safe, and any application of it that makes change *harder* has missed the point.
42

Know the answer?

Join Nobink to answer, vote and build your reputation.