Removing Duplicate Code
Understand why duplicate code hinders readability and maintainability. Explore how to remove redundancy using functions, composition, and inheritance. Learn the DRY principle and how to write clear, maintainable code by refactoring duplicated segments within Python OOP.
We'll cover the following...
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 ...