Don’t Repeat Yourself vs Good Duplication

One of the first lessons in programming is “Don’t Repeat Yourself” (DRY). The idea is simple: avoid writing the same code in many places. However, not all duplication is bad—sometimes repeating something is clearer and safer.

Knowing when to reuse code and when to allow a little duplication is an important skill. The goal is to keep your code clean, understandable, and easy to change.

Chefs preparing meals with a recipe book, and others making quick, similar sandwiches
Imagine a busy kitchen. Some dishes are so complex they use a recipe book to avoid mistakes. For simple sandwiches, chefs make them from memory—even if each chef repeats the same steps.

Real-Life Analogy: Recipe Books vs Simple Sandwiches

In a restaurant, chefs use a recipe book for complicated dishes to keep things consistent. For quick snacks like sandwiches, it's faster for each chef to make their own, even if it means some repetition.

  • DRY is like using one recipe book for all complex meals.
  • Good duplication is like making simple sandwiches quickly.
  • Too much sharing can make simple things confusing.

When to Avoid Repetition

Duplicate code can cause problems when you have to fix a bug or make a change in many places. If something is likely to change, or is complicated, it’s better to reuse code.

  • Extract repeated logic into functions or modules.
  • Keep updates easy by having a single source for important logic.

When Duplication is Fine (or Even Good)

If the code is simple, stable, or just slightly different each time, some duplication is easier to read and manage than forced sharing.

  • Small, isolated duplication is often clearer for simple tasks.
  • Don’t over-engineer just to remove every repeated line.

Final Thoughts

Use DRY to avoid problems, but don’t fear small, sensible duplication if it keeps your code clear and safe. Good judgement is better than following rules blindly.