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.

 
 
 

2 Responses to “Code Duplication”

  1. Eric Wendelin
    06:29 on March 19th, 2008

    I feel your pain, Casey. So now would it be worth it to go back and pull out the common elements or is the effort to do that too much for the benefit. At what point would the cost outweigh the benefits?

  2. Casey Watson
    15:24 on March 19th, 2008

    Long term, yes. But I have found that I tend to get a little carried away on the refactors. Spaghetti code is difficult to refactor while still supporting all of the subtle use cases and behaviors. This is especially true when you throw all of your view and business logic into a single JSP file.

    In Refactoring, Martin Fowler proposes that solid test cases are a requirement to all behavior-preserving refactorings. So I think I need to get some solid tests in place before I can combine the common elements. Otherwise, I am guaranteed to break stuff.

Leave a Reply


There is a fine line between a generic flexible UI and a crappy one:

Got the Chocolate Raspberry Stout in the fermenter. I can't wait to taste it.

Just poured out 10 Liters of overly-carbonated, accidentally-alcoholic, plastic-flavored, homemade root beer. Lessons learned: 3!

Follow me on Twitter