Code Duplication
A while ago I fixed some obscure bugs in one of the search results pages of an enterprise application that I work on. I spent about four hours of focused development time refactoring and cleaning up some of the logic that handles the rendering and paging of the results. The new code worked well.
A couple of weeks later I found myself bug squashing on another search results page. As I dove into the code, I found a nagging sense of deja vu. This page had the same logic errors and mistakes as the page I had worked on weeks earlier. I found myself fixing the same bugs and performing the exact same refactorings as I had before.
I became more frustrated as I realized that the original author had copied all of the logic from the original page. Rather than extracting the common functionality to a reusable location, he took the lazy approach with copy and paste.
This kind of mistake is expensive. By duplicating the code, the cost of maintenance has doubled. Bugs must now be fixed in both places. Merging the common logic after the fact is more difficult than it would have been initially.
We have these wonderful object oriented languages. There are many ways to reuse code. Some of the following come to mind:
- Two subclasses can share common functionality in a parent class.
- Duplicated code can be moved into it’s own class. This can be done in a concrete class or via a static utility class.
