Chapter 19. A Case for Code Reuse

If it can’t be reduced, reused, repaired, rebuilt, refurbished, refinished, resold, recycled or composted, then it should be restricted, redesigned or removed from production.

Pete Seeger

We hear about a mythical thing called “code reuse.” For a while it became incredibly fashionable; another software silver bullet, something new for the snake-oil vendors to peddle. I’m not sold on it.

We often talk in terms of “use cases” when developing software. We also see these reuse cases:

Reuse Case 1: The Copy-Pasta

Code copied out of one app is surgically placed into another. Well, in my book that’s less code reuse and more like code duplication. Or, less politely: copy-and-paste programming. It’s often evil; tantamount to code piracy. Imagine a bunch of swashbuckling programmers pillaging and hoarding software gems from rich codebases around the seven software seas. Daring. But dangerous. It’s coding with the bad hygiene of a salty seaman.

Remember the DRY mantra: do not repeat yourself.

This kind of “reuse” is a real killer when you’ve duplicated the same code fragment 516 times in one project and then discover that there’s a bug in it. How will you make sure that you find and fix every manifestation of the problem? Good luck with that.

Having said that, you can argue that copy-and-paste between projects actually gets stuff done. There’s a lot of it about and the world hasn’t come to a crashing end. Yet. And copy-and-paste code avoids the unnecessary ...

Get Becoming a Better Programmer 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.