Earlier this morning, I found myself trying to help a colleague remove some duplicated code.
There it was. The big acronym: DRY. Don’t Repeat Yourself. The mantra that every aspiring Software Craftsman repeats ad nauseam.
Duplicated code has somehow become, by far, the biggest possible issue in any code base for some kind of developers (not the colleague in this example). And that, to me, is an issue.
What did you say? Did you say DRY is bad?
I did not say that yet. But I will say it now: DRY is bad when it leads to adopting poor solutions to problems, when it leads to bad architected solutions.
A certain degree of duplication is not bad. It actually helps discover abstractions, it helps simplify the design, or at least it helps discover where it is actually necessary to have a point of extension. And this is not the first time I write about this.
In particular, a certain degree of duplication might help you avoid this:
Because, yes, excessive inheritance, or relying on inheritance to solve every single problem is bad. Very bad.
There is nothing like a “one true set of best practices”. There is always more than one solution to a single problem. To the question “what is the best way to do X?” the answer should always be “it depends”.
We have a set of tools to reach for (extension, composition, design patterns, abstraction, interfaces, abstract classes…). There is no right tool for a given problem, but depending on the situation, the same problem might be solved using a different tool or a combination of tools.
Nobody knows what they are doing
Nobody has all the answers, we are all in the process of learning to use our toolset and its applications. There are some things you (like me, and like everyone else) will only learn through experience, if you keep your eyes and mind open.