Deciding when copying a small amount of code is clearer than inventing an abstraction

I have two small functions that share about ten lines of code. I could extract a helper, but their needs are already diverging slightly. Every abstraction I try ends up with extra flags and branching to support both. When is a little duplication clearer than forcing unrelated cases through a shared function? I'm starting to think ‘don't repeat yourself’ is easy to misuse when the underlying behavior isn't actually the same.

  • programming-help
  • copying
  • small
  • amount
81

6 replies · Sort: Best

Best
  1. ED
    dora-e
    5 points

    1 reply

    A lot of people use DRY to mean 'never copy anything,' but that's too blunt. Copying can be fine when the behavior is already drifting apart...

    51 reply

    A lot of people use DRY to mean 'never copy anything,' but that's too blunt. Copying can be fine when the behavior is already drifting apart and the shared code is starting to guess.

    5
    1. PM
      byte_pieda
      2 points

      I think the real test is whether you can change one without wanting to change the other. If yes, they're not one thing anymore.

      2
  2. CS
    charles_5
    4 points

    3 replies

    If the shared code is already forcing flags and branches, that's a sign the abstraction is doing too much. I’d rather copy ten lines than cr...

    43 replies

    If the shared code is already forcing flags and branches, that's a sign the abstraction is doing too much. I’d rather copy ten lines than create one helper that nobody can read.

    4
    1. xiao.si
      1 point

      I usually ask whether the two pieces will still look the same a month from now. If not, duplication is often the honest choice.

      1
    2. GG
      giri_gole
      2 points

      Also, extracted helpers should make intent clearer, not just shorter. If the call site becomes harder to understand, the abstraction is losing.

      2

        This. I’ve seen helpers with five optional arguments that nobody wanted to touch. The duplication would have been kinder to future me.