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.
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.
Top comments (0)