Hacker News new | ask | show | jobs
by 256 2268 days ago
The problem with this in practice is that you're often not the person implementing the 3rd instance. It's some other dev who comes and sees 2 copy/pasted implementations, either figures there's a good reason for it, or is lazy, or is risk adverse, or just wants to get the job done and move on, and copy/pastes it a 3rd time.
2 comments

Explanatory comments that tell the reader to go look for other instances of this pattern are the key to success.

    // AB-20200405 - Hi future developer (probably me),
    // if you're copying and pasting this code, then
    // please take an extra five minutes to locate the
    // other similar instance of this code snippet in
    // the codebase, and refactor both of these into a
    // method first. The other snippet will have the
    // same comment that precedes this one.
    // 
    // Here's what this overly clever snippet of code 
    // is doing, so that when you do refactor it into a
    // method in 2023, you don't miss an important edge
    // case. Ta!
Another life hack: reference the same “AB-20200405” in the other code snippet.
Right, it all falls apart otherwise.
Or, the new dev doesn’t see the second copy, because they gave you the benefit of the doubt, and only apply a bugfix to one copy.

Later, since your team is growing, some other dev applies some other fix to the other branch (which was also copy pasted three times by three distinct devs because “rule of three”).

Soon, you have a dozen copies, and they are all wrong/diverged enough to not be clear copy pastes any more.

I’ve seen this happen more often than not, especially when scaling teams. Since the team is scaling, the original dev won’t always review all the code changes.