Thursday, March 8, 2012

Duplicated Code: The evil twin sister of you favorite function.

Duplicate code is one of the most common code smell we have in our codebase. Its simply we don’t care that much about reusing, we know how to reuse objects, functions, even solutions or component but we are some what careless about removing duplicate code. You would be surprised to know that what amount of duplicated code exists and what are those? Off course there are some obvious techniques to eliminate those.

Here is what Wikipedia has to say about it",

“Duplicate code is a computer programming term for a sequence of source code that occurs more than once, either within a program or across different programs owned or maintained by the same entity. Duplicate code is generally considered undesirable for a number of reasons.[1] A minimum requirement is usually applied to the quantity of code that must appear in a sequence for it to be considered duplicate rather than coincidentally similar. Sequences of duplicate code are sometimes known as code clones or just clones.”

There are two type’s of duplicate code
  1. Blatant –same code appears in more than one places (Example: two methods, two related classes, two unrelated classes, etc.)
  2. Subtle-looks like different code but serves the same purpose
The following are some examples of duplicate code.
  • character-for-character identical
  • character-for-character identical with white space characters and comments being ignored
  • token-for-token identical
  • token-for-token identical with occasional variation (i.e., insertion/deletion/modification of tokens)
  • functionally identical
How duplicate code find the way into our code base?

The process is more than simple. you knowingly introduce duplicate code, and the possible candidate is

  • copy and pest code and use.
  • write similar code (subtle duplication).
  • rather than using library re-inventing the wheel.

There could be thousands of example that can be put down here, but would not be appropriate, but we have the idea, lets go and find duplicate code and eliminate them, it’s a game and we have to play it with huge interest.


The bottom line is that we must eliminate duplicate codes, while doing coding just give a breather to your mind and try to find out if there is already a code there or not that do the same purpose, and could it be refactored in such a way so that it could be used by your case also? Most importantly while working with legacy code we need to be more careful and keep our mind open to refactor a lot to eliminate duplicate codes.


No comments:

Post a Comment