DEV Community

Discussion on: How to write a clean code.

Collapse
 
vilx2 profile image
Vilx2

I'd like to add a few thoughts about that DRY thing. It's a tricky one.

Over the years I've come to the realization that sometimes it's actually more readable to duplicate code on purpose. Like in your example I would totally go for the "bad" code because it's still way shorter than the "good" code. Even though it's duplicated, the reader will immediately see what's going on in MyComponent without having to mentally go forth and back between MyComponent and MyOtherComponent.

OK, I understand, this is really just a minimal example of the DRY principle so perhaps I shouldn't pick on it. But I often see similar situations in real life too, where good-intentioned colleagues have created one-liner methods (or even classes!) that are called in one or two places only, yet they require me to jump all around the place before I finally get the full picture of what MyComponent is actually doing.

Another case for violating the DRY principle is when you have two pieces of requirements that are almost - but not quite - the same. That's really a tough choice. There are three ways you can tackle that - duplicate code and make minor modifications in each place; put common code in a base class and specific code in child classes; or just pepper the code with a spiderweb of IF statements. All three are ugly, but I tend to find that code duplication is actually the lesser evil of the three a lot of the time. Whenever you're reading this code, most likely you'll just be interested in one of the versions, so having the other two out of the way is actually easier. And the thing about the different versions is that they tend to get even more different over time, so keeping up with the other two approaches you end up adding more and more abstract methods or IF statements. And that in turn makes it even less legible.

Collapse
 
ishanbagchi profile image
Ishan Bagchi

I understand you. Here in my example in OtherComponent it is ok to change just 2 lines if there is a mistake. Now just imagine if I had a few more lines of OtherComponent, and I had to change the class name, it would be so much pain to remove all of them and replace it with the new class name. Whereas in MyOtherComponent I just have to change the class name in just one line.