This week lets take a look at a(nother) useful principle, the Don’t Repeat Yourself (or DRY) principle. The goal here is to get an idea of how the principle works and then aim to incorporate it into your day to day development activities. Remember to try to combine it with the other principles we’ve looked at, for example the Single-Responsibility Principle from the SOLID principles.
So where’d this one come from?
Introduced by Andrew Hunt and David Thomas in their 2000 book “The Pragmatic Programmer” they define DRY as
” Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.“
What we are basically aiming for is don’t say (following Uncles Bobs tell a story advise) or do the same thing twice. If you have some logic that performs a useful job, or even if its not that useful, don’t repeat that code. Combined with Single-Responsibility you could wrap that it up behind a class or method and have a single definition (“authoritative representation”).
I read a quote once that is quite good, “The only bug free code is no code” another is “Code that doesn’t exist is code you don’t have to debug” (can’t remember the original authors). Essentially what both of these statements are telling us is, write as little code as you can to get the job done. By following DRY we can shrink our code base by reducing repetition and therefore reduce the chances of bugs or introducing bugs through changing the same piece of code found in multiples places.
Another benefit we get from DRY is if you have a block of code duplicated throughout your code base and you need to make a change to that block not only do you have to go and update all blocks but there’s a chance a bug can be introduced through this change (at the end of the day we’re only human). Now if that code block was held in one place, meaning only one update was required we save time and reduce the chance of introducing bugs.
One example is say we needed to modify a piece of data using the following steps:
const int TEMP = 10; double x = 30; double y = 5; x = x * TEMP; x + y; x / 10;
Now instead of duplicating this “important” bit of code we can wrap it in a suitably Named class or method and simply call that.
That’s it really, if you find yourself writing the same piece of code more than once consider if it may be worth extracting all instances of that block.