Problems when you don’t Refactor Rails: Code Duplication

I’ve written about refactoring Redmine here but I feel I haven’t explained why refactoring is important. The most common reason is to remove code duplication.

Code Duplication

Code duplication occurs when an application has two sections of code that are identical or almost identical. Sometimes this happens because the application requires the duplication but most of the time the duplication if from a developer being lazy or not having “enough time” (I’ll address the “not enough time” excuse later). Two big problems come from code duplication, an increased modification cost and bugs from branching code.

Increased Modification Cost

This problem is a tax that every future developer has to pay. Instead of preventing the code duplication upfront, the original developer tried to save time but just copying and pasting the code. When the next developer comes along, they now have to spend more time to modify that code, since there are now N copies of the code. When they forget to modify one copy, that causes the second problem.

Bugs from Branching Code

When there are N copies of code in an application, they all have to be modified at the same time. Otherwise, you’ll end up with a bug fixed in one copy that still occurs in another copy. Repeat this a few times and now you have bugs 2 and 4 fixed in Healthly::Recipe and bugs 1, 3, and 7 fixed in Vegan::Recipe. So are those bugs really fixed?

No

At the worst time possible, someone will run into bug 1 in Healthy::Recipe crash your application, melt your hard drives, alert Skynet, and end the world. Or probably just upset the user, your customer, and make you rush to patch the code.

As the copies diverge more and more, refactoring them back to a common code base gets harder over time. This is one of the biggest problems I have when I’m refactoring Redmine. If I prevented the duplication right from the start or even refactored it early on, the code today would be in a lot better state. Instead the duplicated code has grown, diverged, and takes extra work to clean up.

The sooner you refactor your code duplication, the easier it will be to keep it under control.

Like this post? Read the rest of the Problems When You Don’t Refactor Rails series

  1. Problems when you don’t Refactor Rails: Code Duplication
  2. Problems when you don’t Refactor Rails: Test Duplication
  3. Problems when you don’t Refactor Rails: Wild Estimates
  4. Problems when you don’t Refactor Rails: Lowered morale
  5. Problems when you don’t Refactor Rails: Lower Participation