How much should I be worried about keeping my code D.R.Y.?

Hey just looking for some general advice, I’m wondering what kind of compromises I should make when keeping my code D.R.Y, in my program I have a command manager that accepts enums, and it kind of works like this

if command is “move items”
for loop etc.

if command is “delete items”
code, repeated for loop and variables

I’m just wondering how much I should worry about keeping things D.R.Y. in this instance, as the function I have here is super organized with the small drawback that it is not really that D.R.Y at all as if there is more then 10 commands they all end up kind of using the same code. what should I worry about with DRY, is it that it will be difficult to change later, or is it performance, or is it readability. because I could create complex if statements with lots of && and || variables and re-factor how I have it, but it works as is. just looking for some insight on when DRY almost becomes redundant. thanks

I would probably make the “move”, “delete” etc operations methods of the thing that is holding the “items”. (This could lead to repeated code too, but at least it would be elsewhere than directly in the command handler code.)

It’s certainly not a cut and dried answer, but DRYing your code is important. One of the newer things that comes into play in finding an answer to repeated code are lambdas. I also had some code that iterated over items in a list, doing slightly different operations, which I turned into a forEach type function, with a lambda as a parameter for the operation to be done. Worked like a champ, reduced line count by a bunch, and made future operations super simple to implement. If the context of the shared code is all in one function, you could also make the forEach a lambda within that function too.


If you write bug-free code, DRY is nothing to worry about :wink:

It will become important, once you come back to the code to find mistakes.

And it will become crucial if you try to refactor later, and you have to figure out, if a similar looking block of several lines of code is actually a copy, or if there is something intentionally different.

Copy and paste is like eating chocolate, gives short pleasure but regrets later