When is it okay to duplicate code?

Seth Livingston
2 min readMar 26, 2022

--

Photo by ETA+ on Unsplash

Duplicates

Duplicating code became a capital crime when Andrew Hunt and David Thomas published The Pragmatic Programmer in 1999 — one of the most popular and revered books in software engineering.

In the section titled, “The Evils of Duplication” [emphasis added], the authors introduced the DRY principle:

  • Duplicating code creates multiple sources of truth.
  • Maintaining multiple sources of truth is a nightmare.
  • Don’t Repeat Yourself (DRY).

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

Rock solid advice. If you’ve ever had to fix a bug in multiple copies of the same code, then you know how maddening it can be.

Hasty abstractions

Unfortunately software engineers everywhere took this advice to the extreme and created a new problem: unnecessary abstractions. Every time a software engineer detected so much as a few duplicated characters, they created a new (and often flawed) function, file, class, module, or system.

Sandi Metz tackled this problem in 2014 when she posted a controversial slide at a Ruby conference:

Duplication is far cheaper than the wrong abstraction.

Kent C. Dodds gave this idea an acronym: Avoid Hasty Abstractions (AHA).

Rock solid advice. If you’ve ever had to fix a bug tangled up in poorly-designed abstractions, then you know how exhausting it can be.

So when is it okay to duplicate code?

  1. It’s usually not okay. It really does create maintenance nightmares. And it’s especially not okay if you’re aware of the duplication and too lazy to do something about it.
  2. It’s okay to duplicate code when the abstraction required to fix it would be an even bigger nightmare to maintain than the duplicated code.
  3. It’s okay to duplicate code when you’re collaborating with others who agree that it’s okay to duplicate code. And if your collaborators don’t agree, then work with them to design the right abstraction.

To summarize: don’t repeat yourself, avoid hasty abstractions, and collaborate when those two principles collide.

--

--