Wait, wait!!! Are we really done here? Of course, the request is fulfilled but it doesn’t seem very correct from a technical point of view. It is full of duplications everywhere (although the code is just a few bunches of lines). WET is everywhere (Write Everything Twice: the opposite of DRY).

Let’s do some refactoring here. These two methods mainly do the same and the only difference is the final output. A good start here is to extract the body to a new method.

This way we’ll have a single source of truth: the report will be only created in a unique point. The other methods will have the single responsibility to decide what to do with the report.

Rule of three

This was a simple example but I tried to show the importance of avoiding duplication and how we could deal with it. Of course, sometimes the duplication may not be so easy to spot it. Or to get rid of it you may need some more complexity like applying some design patterns.

One important code refactoring is the Rule of three. To repeat once the same code may be ok. But the third time we build the same code, it’s time to refactor and fix the duplication.

Conclusion: Don’t Repeat Yourself

With all these steps, WET has been removed from our code.

If the report needs any update, it will only be done in one single point. No need to change the same in different places anymore.

The small duplications have been also removed. The methods have meaningful names which explain what they do. Better code.

These methods may be extracted to some helper libraries with unit tests.

Let’s have DRY principle in mind the next you write some code.

But don’t forget the Rule of three!

If you are interested in receiving more articles about Don’t Repeat Yourself principle, don’t forget to subscribe to our monthly newsletter here.

If you found this article about Don’t Repeat Yourself principle interesting, you might like…