What is the DRY principle? Why is it useful to follow?

DRY stands for Don’t Repeat Yourself.

It is a very general principle that everyone should keep in mind when writing software. It means that we should avoid repetitions in our code as much as possible. By repetitions we do not necessarily refer to a set of lines or whole lines, it could just mean a string literal, a number, or any smaller fragment of code.

Let’s see a simple example where we use a short formula to calculate a value.

int result = (pointsInFirstRound + pointsInSecondRound) * bonusMultiplier;

It is possible that this formula will be used in multiple places. In order to follow DRY, you should extract it to a method.

private int calculateResult(int pointsInFirstRound, int pointsInSecondRound, int bonusMultiplier) {
    return (pointsInFirstRound + pointsInSecondRound) * bonusMultiplier;

You can call this method any number of times.

Advantages of DRY

Less work

By not repeating code, you have less work to do. If you have a logic that spans 10 lines and you extract it to a method. You will need 1 line instead of 10 lines at every occasion where you use it.

Better maintainability

There is always a chance that your code will need to be changed because a bug is found and you need to fix it or a change request came in. If you have the code in only one place, it’s much easier to modify as you only have to do it once.

Less chance to break the code

If you have to do a change in 10 places, there is a chance that you’ll make a mistake. If the logic is only in 1 place, you have a much higher chance of getting it right.

Better testability

If you extract a piece of code to a well-separated and reusable unit, then unit testing it is easy. You can you test the extracted code and you can mock that logic at every occurrence.

If you have that block of code in several places then you have to take it into account at all of its occurrences. So using DRY makes testing easier.

Better readability

As a result of following DRY, you will have less and better-structured code that is easier to follow.

Disadvantages of DRY

DRY is a great principle to follow but if it is overused it can be a source of issues. If you are trying too hard to make sure that nothing is repeated, it is possible that your code will become too complicated and hard to understand.

You have to weigh the benefits of DRY. Sometimes it’s better to repeat some code if it clearly helps readability a lot.