Don’t repeat yourself is a principle of software development aimed at reducing repetition of code and replace it with abstractions.
DRY principle says:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
If you’ve duplicated a bit of code in many places, the DRY principle tells you to extract the duplication into a single common method and then invoke this new method in place of the old code. DRY promises that if you do that, you will save money later if the behavior of that chunk changes.
But we should recognize, that DRYing out code is not free. The price you pay for DRYing out code is that the invoker of the new method no longer knows the result, only the message it should send. It inserts a level of indirection between the place that uses behavior and the place that defines it, and layers of indirection make the details of what’s happening harder to understand.
Besides, if the new abstractions are created are incorrectly, they can cause more confusion than help. That’s why Sandi Metz says:
Duplication is far cheaper than the wrong abstraction
Therefore, instead of prematurely DRYing out your code, you should wait until you fully understand the problem you are solving and you need to add a new feature that really require remove that duplication because maintain it would be costly than remove it.
DRY makes sense when it reduces the cost of change more than it increases the cost of understanding the code.
- Book The pragmatic programmer where this principle was first formulated.
- Book 99 Bottles of OOP by Sandi Metz & Katrina Owen.
- Wikipedia DRY definition.