DEV Community

Cover image for DRY principle could be harmful. Here's why.
Alex Pushkarev
Alex Pushkarev

Posted on

DRY principle could be harmful. Here's why.

Many people suggest the DRY principle (which stands for Don't Repeat Yourself). While in theory it is a solid idea and leads to code reuse, it can also lead to very subtle and hard-to-track unnecessary dependencies between code, which could create an unreasonable risk of regression.

Let's consider an example where I am going to reuse some logic from class A in class B. I can either copy-paste it or I can extract it into the utility class. DRY would suggest the second.

But what if at some point I will need to change class B behaviour, but not A and this behaviour is part of the extracted logic?

Depending on the code base I am either completely screwed or could be screwed.

Image description

1️⃣ If I have good test coverage I am most likely in the "could be screwed" place. While the chance of breaking functionality is fairly low, the software isn't only about functionality. I could still break non-functional requirements, such as memory use or performance requirements.

2️⃣ If I don't have good enough coverage (and that I think is the most probable place to be) - I AM screwed. Unless I track each and every usage of the extracted logic - not only I could break non-functional requirements but I could break functional requirements as well - and never know it until it is too late.

So, don't use DRY blindly. It doesn't mean you should not extract common logic, but it does mean it should never be your default course of action.

👉 If you find this post useful please consider liking it and following me for more content on code quality.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay