The “don’t repeat yourself” principle is well established, but over-aggressive refactorizarions to extract common code are also widely known for creating hard to maintain code due to the introduction of tight coupling between components that should not be coupled. A passing resemblance between code blocks is reason enough to extract them away, even if that ends up breaking Liskov’s substitution principle.
To mitigate problems caused by DRY fundamentalisms, the “write everything twice” (WET) principle was coined. WET works by postponing aggressive refactorizarions, the kind that introduces complexity and couples unrelated code just because it bears some resemblance, by creating a rule of thumb where similar code blocks showing up twice in the code should not be refactored, and only code that shows up multiple times should be considered for this task. However, this rule ignores context and nuances, and can dissuade developers from cleaning up code.
So, where do you stand on the topic? How do you deal with duplicate code? Do you follow any specific rule of thumb?
If I find myself repeating more than twice, I just ask “Can this be a function”. If yes, I move it there. If not, I just leave it as it is.
Life’s too short to spend all day rewriting your code.
I’ve never heard of WET, but that is exactly the process I preach to my team. Refactor only once the same code block is used 3+ times as that tends to define a method that is a utility and not business logic specific.
This method has worked well in the past.
I call this my “rule of three” - I wait until I’ve seen “something” three times before deciding on an abstraction. Two isn’t enough to get an idea of all the potential angles, and if you don’t touch it a third time, it’s probably not important enough to warrant the effort and risk of a refactor
I prefer the FP approach where I create smaller functions that I compose together in larger functions or methods wich rarely repeat themselves elsewhere identically. Forcing extractions and merging of such functions often leads to weird code acrobatics.
What does the code represent? What does it concern?
Focusing on the code and pattern too much may mislead. My thinking is primarily on composition and concern. The rest follows intuitively - fee with risk, gain, and effort assessment.
I’ve had occasional instances where code duplication is fine or not worth to fix/factor. But I feel like most of the time distinct concerns are easy and often important to factor.
I’ve habe
found the german.