What is the DRY principle?
Reading time: 2 minutes
Why should I care?
The 'DRY' Principle - or 'Don't Repeat Yourself' is one of the most commonly quoted, but most commonly misunderstood pieces of guidance in programming.
While the premise is simple, it can lead to over-abstraction and hard to maintain code when misinterpreted.
Don't Repeat Yourself
The DRY principle was introduced in the book The Pragmatic Programmer in 1999.
The original definition is:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
So what does that mean?
Let's start with what it does not mean...
Misunderstanding the DRY principle
DRY is commonly used as an argument against writing the same line of code twice.
That's understandable. If we have to copy/paste some code we've already used, we immediately want to move it into a common abstraction - it's in our nature as programmers!
But writing the same line of code twice is not necessarily bad, and it is not what DRY is talking about.
Here's what one of the authors of the book that coined the term - Dave Thomas - said in a podcast interview:
DRY has come to mean “Don’t cut and paste”, but the original “Don’t repeat yourself” was nothing to do with code, it was to do with knowledge.
The perils of over-abstraction
There are some valid reasons to write the same block of code twice; the code might do the same thing but for different reasons or in different contexts.
Next time you're tempted to abstract two areas that look similar, ask yourself:
Do these sections of code have different reasons to change in future?
If so, abstraction might not be the right choice.
Once you've abstracted that code, you can't change one area without affecting the other - they are now coupled.
Maybe that's the right decision, and you might choose to abstract them anyway, but DRY doesn't insist that you should.
DRY is about 'knowledge'
DRY is about ensuring that any change to the functionality of your code happens in one place only.
We've all worked on code where a simple functional change needs far too many code changes.
If I want to change the way we format a user's name, I have to change it on the profile page, the confirmation emails, the invoice generator, the administration dashboard... you get the idea.
This is what DRY is warning against; there should be one place to make this change. The knowledge of how to format a user's name should be contained in just one area of your code.
Next time I need to make that change, I know exactly where to go. Otherwise, it's only a matter of time before I forget one of the many areas I need to change and cause a bug.
Want to know more?
Check out these links: