You can copy and paste code.
There are times when it is the right thing to do. We are taught not to do it because, more often than when it is the right thing to do, it is the lazy thing to do.
It is not the right thing to do when you’re copying an idea that, if you change it, will have to be changed everywhere you copy it. If everywhere you copy it it needs to vary independently then it’s good to copy.
You can dedupe code
The thing that makes not-copying difficult to write is you’ll need a good name. Avoiding creating bad names is good but avoiding creating good names is bad.
If we can get a good name out of you then the code becomes easier to read. You’ve discovered a useful abstraction that saves readers time.
Sometimes duping is required
However, sometimes code expresses a different idea that varies independently and just happens to look the same. In this case duplication is no sin.
You can’t tell by looking at the copied code. Being the same code character for character isn’t the sin.
Just because x
and y
both happen to equal 1
doesn’t, on its own, mean one of them has to go. No, but if you had a rule that said x
must equal y
then you should question whether you really need y
.
Uncertainty
What if you can’t predict the future and aren’t sure if it needs to vary independently? In that case, consider avoiding copying simply because it makes it harder to see what you have done. Requirements change isn't the only thing that forces change. Discovered bugs force change as well. It's not fun to find you've copied a bug to a bunch of different places and left yourself no easy way to find every place. Also there's refactoring. Your copy might be an easy to detect dupe now but then someone refactors it and suddenly it's a dupe (still does the same thing for the same reasons) that looks completely different.
When you give a snippet of code a name and reuse that name you are making the reuse explicit, ensuring that each use changes together, and hopefully used a good name on a good abstraction. When you don't need those features, copy as you please.
Try again later
You might read this and conclude that since these features were desired the junior developer made a mistake. Hold on. Often the easy way to reuse code is to first copy it, figure out what code needs to be created to support it, and test that it really does what you need it to do. Then consider factoring it out with a name and abstraction (method, object, etc). Yes, copy and paste can be a good first step to explicitly reusing code. Which is exactly what you used it for.
Mark your path
But this only works if you know where all that copying happened. You were lucky you could find it. People with questions and bathroom trips interrupt at the most inconvenient times. So if you want to be a casual copier consider adopting a habit of documenting where your code came from when you copy it. A quick little comment can save your bladder and ensure that the reuse is detectable.