DRY can be a useful guideline but please don't enforce absolute, strict adherence. Sometimes a little duplication is okay and helps avoid complex, inflexible abstractions.
DRY can be a useful guideline but please don't enforce absolute, strict adherence. Sometimes a little duplication is okay and helps avoid complex, inflexible abstractions.
Sandi Metz had an awesome presentation about this during a Rails Conf.
"Duplication is far cheaper than wrong abstraction"
https://www.youtube.com/watch?v=8bZh5LMaSmE
Her blog talking more about the assertion:
https://www.sandimetz.com/blog/2016/1/20/the-wrong-abstracti...
My thought process has always been: If there is a common piece of functionality to be shared, then refactor. If it just happens to be the same, maybe leave it.
… 2–3 times. Not ok to repeat them 1000 times.
A common DRY failure is when you abstract one function, then you find another place you can put it if you just add one more parameter, then you find that if you add two more parameters it fits here and here, and repeat until you've got a 12-parameter monstrosity loaded down with if statements and conditionals and block of code whose sole purpose is to preprocess the optional arguments into something the rest of the code will take... but what got you there still isn't the DRY principle, but that the repetition was actually never there in the first place. In the worst case you can end up with two or more things that should actually be entirely separated functions.
I've personally done that once myself; tore one of these functions up into two functions literally by copying and pasting the lines of the original into the two new functions... and there was virtually no line that went into both the new ones. Post simplification the sum of the two new functions was about half the length of the original. And it wasn't anybody's "fault"... it has just grown that way, one commit at a time, over dozens of commits.
DRY is still really important, but there's a lot of complexity/wisdom in what the true meaning of "repeat" is.
Sometimes doing DRY means you've nicely separated out and encapsulated the common code that can be checked just once in isolation. Sometimes doing DRY means you end up with a complex abstraction that is hard to understand on its own.