Sometimes You Should Repeat Yourself

Dry principle is great but should not be abused

Tal Joffe
Talking Software
2 min readJan 7, 2023

--

Source: https://www.flickr.com/photos/hobgadlng/7695466002

When asked about coding best practices and examples of “Clean Code” patterns, people often mention DRY (Don’t Repeat Yourself) as one of the first answers.

In many cases, it is true that we don’t want many duplications of the same logic in our code because we can write code faster, have less code to maintain etc.

My argument is that elimination of duplications, or keeping your code DRY, if you will, is not the goal on its own and if not used correctly can be a problem.

A common example of DRY related problem could be a bloated “util” folder in your project that was put there to store “common” logic (remove duplications), but turned over time to a landfill of cryptic code. The matters get worse when those util folders become packages of their own and now testing and maintaining becomes a real pain in the neck because there is no context on how the util methods are being used.

Something to remember is that the fact that code looks the same, or is actually the same now, doesn’t mean it will stay like this forever. Code always changes and evolves as new requirements come in and if the duplication removal created unnecessary coupling between unrelated logical component that will lead to complexity that will grow bigger the further the two logical components will drift from each other.

If we start our implementation with a design that has a clear Separation of concerns (SoC) between different components each with its own single reason to change (following SRP — Single Responsibility Principle), we could know which things belong together and which things do not so that we follow DRY but with some guardrails.

In summary, not all principles were created equal and while DRY is a nice one it is useful only when you have established a proper design and know what code belongs where, so you don’t accidentally couple components together in an effort to remove duplications

If you are not sure how to approach creating a design, you can check this post I wrote — link

--

--

Tal Joffe
Talking Software

Interested in software, people, and how to bring the best of them both @TalJoffe