Removing Duplicate Code

Learn why duplicate code is problematic and explore strategies to prevent it.

Often, the code in management-style classes such as ZipReplace is quite generic and can be applied in a variety of ways. It is possible to use either composition or inheritance to help keep this code in one place, thus eliminating duplicate code. Before we look at any examples of this, let’s discuss some design principles.

Why is duplicate code a bad thing?

There are several reasons, but they all boil down to readability and maintainability. When we’re writing a new piece of code that is similar to an earlier piece, the easiest thing to do is copy and paste the old code and change whatever needs to be changed (variable names, logic, comments) to make it work in the new location. Alternatively, if we’re writing new code that seems similar, but not identical, to code elsewhere in the project, it is often easier to write fresh code with similar behavior, rather than figuring out how to extract the overlapping functionality. We sometimes call this copy-pasta programming because the result is a big mass of tangled noodles of code, like a bowl of spaghetti.

Get hands-on with 1200+ tech skills courses.