Get Rid of Duplicated code in Application

Posted by admin on February 6, 2008 under Programming | Comments are off for this article

Duplicate code makes the programs hard to understand and maintain. Most of the applications have about 10% to 25% duplicate code. In X Window System about 20 percent code is duplicated. Java Buffer Library in JDK version 1.4.1 duplicates more 60 percent code.

Problems with duplication

    Computer

  • Errors get spread everywhere in the code but fixes do not.
  • Evolution of code is not reflected everywhere – Some places might be skipped.
  • Some places are forgotten and do not get updated.
  • Code bloat – code gets much bigger since there is no sharing.

Where to look for code duplication?

  • In the same class – several methods that repeat a number of instructions.
  • Between siblings – two classes that share a common super class.
  • Methods in siblings can repeat a number of instructions.
  • Between unrelated classes – classes not in a hierarchy can still repeat the same sets of instructions.

How to get rid of duplicated code

  • Apply the methods mentioned below during development or once you notice duplicated code.
  • In the same class – Extract duplicated statements into a method that gets used in all the places that duplicated the code.
  • Pull up common methods to super class. You might need to create an intermediate class.
  • Introduce template method to capture common structure in code.

Comments are closed.