When should you repeat code?
Don’t Repeat Yourself (DRY) concerns shared knowledge. Two policies can use the same arithmetic without having the same owner or reason to change.
Here WET means Write Everything Twice: tolerate duplication while policies differ. A factory can share the calculation while keeping policy configuration separate.
Understand it. Then fix it.
The useful part
Don’t Repeat Yourself (DRY) concerns shared knowledge. Two policies can use the same arithmetic without having the same owner or reason to change.
Make the rule explicit
Here WET means Write Everything Twice: tolerate duplication while policies differ. A factory can share the calculation while keeping policy configuration separate.
const makeDiscount = (rate, cap = Infinity) =>
price => Math.min(price * rate, cap);
const employeeDiscount = makeDiscount(0.1);
const promoDiscount = makeDiscount(0.1, 25);Code blocks are teaching excerpts. Keep the surrounding error handling and application requirements.
Save the code excerpts ↓Read the full transcript
When should you repeat code? I merged two discounts into one helper. A promo cap just cut my employee benefits. DRY means Don’t Repeat Yourself. Share a rule, not just matching code. Here, the promo cap went into the helper both discounts called. So should I repeat myself, or use a factory? WET is often expanded as Write Everything Twice. Here, keep two small functions so independent rules can change separately. Only the promo gets the cap. A factory is another option. It returns a discount function with its own rate and cap. Infinity means no cap. Reuse the math, configure the policies separately. Both designs give $100 off for employees, $25 with the promo. Choose simple separate rules, or a factory when the shared calculation is stable. Test both policies. I saved two lines. Lost $75. Management called it a performance improvement.