When to copy/paste
Problem: I have two things working similarly, what is the best architecture?
Answer: you don’t know yet, just copy-paste and see what happens next.
Rationale: duplication is much cheaper than the wrong abstraction.
— — —
Here’s what I suggested to an (optimistic, motivated, skilled) beginner: you should just copy-paste the code because you probably won’t reuse it.
You notice that you are confused, you can’t settle on the “best” approach: that’s because there is no way to decide on that yet.
Copy-pasting is fast and easy to do, its dangers are known:
- it settles standards: bad code will be copied
- it’s easy to copy X and replace the variable name N times, just to forget the N+1
But here’s what I guessed would happen: the things that look similar right now (things like reviews, comments, scores, life cycles) will probably turn out different: one has more fields, one has some manager validations, one has automatic behaviours…
— — —
So here’s what to keep in mind: if you happen to copy-paste this one more time then it’s a smell and you should refactor, but for now you’re probably doing wild guesses and any modelling is good enough.
I would hate for you to have a “super clever design” (which we can’t guess right now) then just make complicated solutions for the new needs to fit the old cleverness:
- if you find a third thing which is super-similar and you change too often: refactor
- if it happens that you’ll need other things, in a similar way: refactor
- if it happens that X and Y are actually different in the long run… at least you didn’t start the hard way and delivered fast :)
Typical Tetris Effect!