Chapter 28. Copy-Paste as a Principled Engineering Tool

Michael Godfrey

Cory Kapser

〈Ctrl-C〉 〈Ctrl-V〉 Every software developer knows that copy-paste—aka code cloning—is a bad habit, yet we all do it. We might wince, knowing that we’re being a little lazy, but we usually manage to convince ourselves that the programmatic ends justify the means. After all, a lot of the time it’s simply quicker to copy and paste a piece of existing code that does something similar to what we want, and then carefully clean things up afterwards.

Yet the act often makes us feel uneasy. We know that good intentions don’t always manifest themselves as concrete actions and, like the proverbial potato chip, we know that it can be hard to stop after just one. And we suspect that by taking the easy way out, we’ve perched our project on a slippery slope that can lead to decaying design and inconsistent maintenance. Certainly, most of the expert advice out there says that code cloning is bad news, full stop. But how bad is it? And how do we know?

So we may pause to reflect, and perhaps ask ourselves some questions: just how harmful a practice is code duplication anyway? Does it lead to demonstrable maintenance problems in the long run? What motivates its use in the first place? Are there different reasons that developers duplicate code, and might some uses be more defensible than others? Is code duplication ever a good idea? Can code duplication be managed successfully, and if so at what cost?

These are good questions, ...

Get Making Software now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.