DRY Considered Harmful

Aug 16, 2021

DRY stands for "Don't Repeat Yourself" and has been handed down as one of the unbreakable programming principles for decades. It shows up in other places, such as the "rule of three" – "if you have to do the same task three times, automate it."

This advice can be harmful and sometimes downright wrong, especially when applied dogmatically.

A little duplication is often better than a little dependency.

So, why are programmers so susceptible to misusing DRY? The concept is often applied dogmatically by programmers because they have a bias for abstraction. Many times, it's challenging to know the abstractions a priori. Deeply nested abstractions make debugging difficult because of too many layers of indirection. All abstractions are leaky. The map is not the territory.

We're often too quick to carve out microservices and create service boundaries where there shouldn't be. We prematurely optimize when the requirements aren't finalized (spoiler: they never are). Duplication is a convenient but not the best source for discovering abstractions. The wrong abstraction at a lower level creates an exponentially worse dependency hell at higher levels.

Plato's allegory of the cave comes to mind. Plato describes prisoners who have been kept in a cave their entire life, facing a blank wall. On the other side, a fire casts shadows of objects against the wall. To the prisoners, the shadows are all they know. When finally released from the cave, they start to realize they haven't been observing actual objects but just representations of them. The lesson is one about higher-level abstractions and how we come to understand things truly.

A treatise against DRY is not one against abstraction. It is one in search of the right abstractions. In Plato's cave, some freed prisoners reject reality and stay in the caves, worshiping the shadows. We must look for the true abstractions, not the convenient ones.

Leave a comment on Hacker News.