The DRY Acronym
DRY stands for “don’t repeat yourself”. The DRY principle is one of the most important principles in software development, if not even the most important. Whenever you write or read code and find repetition in it, chances are high you or whoever planned it, didn’t plan well enough.
What’s the problem about code repetition?
Code isn’t static. When you write code twice you have to test it twice and if you have to change it afterwards you also have to change it twice, in fact we already got the four-fold effort to invest. There is also a large chance, you miss the second occurrence. Seriously, nobody can remind himself to every line or routine of code he wrote in a project, at least if it isn’t an insanely small one.
There is a word for software that isn’t changed: HardwareUnknown author
In fact, redundant code is not only one of the most common causes for bugs, it’s also the cause for unnecessary complex or at least long code. The DRY principle helps you to avoid these problems.
Example of duplicated code
Whats wrong by changing this to:
I am aware that this is a rather simplified example and that the solution doesn’t apply to every problem, but that’s not the point. Fact is, by generalizing concepts and for example moving redundant code to functions you save time and spare potential bugs. If applied correctly it may also increase the readability of your code.
How to apply the DRY principle?
There is no general concept that allows you to always spare repetition, but there are steps that may help you to minimize it.
- Plan thoroughly
By planing your program or software carefully you may identify patterns and generalized concepts in an early stage.
- Review frequently
Review your code frequently, or even better let someone else review your code (That will also ensure your code doesn’t exceed a certain level of illegibility).
- Use tools that support you
Depending on how large your project is, it’s nearly impossible to find repetition manually. But there are tools that allow you to find repeated code anyway. For instance PyCharm¹ offers a duplicates tool window that allows you to identify code repetition.
I am a developer and entrepreneur from Germany. I chose studying computer science because I love building things. I am of the opinion that there isn’t one truth (especially for computer science concepts) and whoever claims so isn’t that trustworthy in my eyes. I constantly try to improve things and myself. In my spare time I support businesses by offering them most of my services for free. Beside that I am kind of addict to e-learning courses.
Book Recommendations on Clean Code (Affiliate)