DRY and YAGNI
Shelfwise raised its member discount from 10% to 15%. The cart showed 15%, the invoice still said 10%, and the mobile app used 12% from some older experiment. The same business rule had been written in three places. Meanwhile, a teammate spent a week on a plugin system for "future payment methods", and Shelfwise still only takes cards. Two principles cover these two opposite mistakes.
The rule
Each fact lives in one place; build nothing before it is needed.
DRY — Don't Repeat Yourself. Every piece of knowledge in the system should have one clear home. DRY is about knowledge, not about text that looks alike.
MEMBER_DISCOUNT = 0.10
def member_price(total):
return total * (1 - MEMBER_DISCOUNT)The cart, the invoice and the API all call member_price. The next change is one edit.
Two functions can look similar and still not be duplication. Shelfwise's postcode validator and phone validator both loop over characters, but they encode different rules owned by different people, and they will change for different reasons. Merging them would couple unrelated things: a fix to one would risk the other. A popular rule of thumb is to wait for the third copy before extracting, so you can see what is truly shared.
YAGNI — You Aren't Gonna Need It. Do not build features, options or extension points for needs that have not arrived. Speculative code costs time to write, test, review and maintain, and when the real need arrives it often looks different from the guess.
YAGNI does not mean "write rigid code". Clean, small, well-named code is easy to extend later. YAGNI says: keep it easy to change, but do not make the change yet.
The shortcut
For a suspected duplicate, ask: if this rule changed, would every copy have to change together? Yes: it is one fact, give it one home. No: leave the copies apart.
For a proposed feature, ask: is anyone asking for this today? If not, write it down and move on.
total * 0.9in three filesIf the discount changed, all three must change together. One fact, so extract
member_price.
The trap is "DRY at any cost": a single over-clever function with five flags that serves ten callers who only looked alike.
Drills
Answer fast — trust the rule.
What does DRY say should exist only once?
The free-shipping threshold 500 appears in checkout, the banner text and the shipping calculator. What should you do?
A teammate wants to add multi-currency support "in case we expand abroad". Nobody has asked for it. What does YAGNI say?
Which is a sign that DRY has been taken too far?
Remember
- Each fact lives in one place; build nothing before it is needed.
- Ask: would every copy have to change together? Is anyone asking for this today?
- Trap: merging look-alike code into one flag-heavy function.
