What’s so bad about copy and paste? It makes it so easy to get things done quickly!
The problem is that it’s a lazy, thoughtless habit that disrespects the next developer who had to come in and change the code after you.
Think about it: how does a legacy code base get to be so hard to maintain?
So let’s say I come upon a piece of code that does almost what I want. It just needs a little extra functionality. I copy it, make some changes to get the result I want (usually by adding a flag), and I’m good to go! And since that previous bit of code was already tested, I didn’t bother to add any unit tests! What a win! And I didn’t even have to think very hard.
But something doesn’t feel right. And there’s a good reason for that: I’ve just made it many times harder for the next developer who has to come in and read that code to do so.
The next developer doesn’t know that code had been copied, so if there was a problem in the original code, they won’t know to make changes to my code as well. Now we have a time bomb waiting to explode.
Not only that, but I’ve made the code harder to read. Rather than extract out the separate functionality to another class, I’ve muddied the purpose of the original one with extra functionality. I have two similar pieces of code that do almost the same thing. So now every time someone wants to use that function, they have to read through at least two bits of similar code to see what they do, how they differ, and which one they will need to use.
And as if that weren’t bad enough, I’ve made the code harder to modify in the future. Anyone wanting to modify any functionality there will have to try and understand the code, figure out why there are multiple slightly different versions, and then come up with appropriate tests to ensure the function continues to work after any modifications are done.
And since I am often that next developer, some months later, I end up cursing my old self.
But I put in comments explaining the new functionality. As if that really helps!
Ok, so copy/paste is evil and horrible and anyone who does it should feel really bad. So what should we do instead?
We will discuss a few approaches to that in future posts.

