It can be recognized by two blocks of code doing the same thing. It is a pure copy-paste or copy-paste-adaptation from one part of the code to another part of code. Besides that, the duplicated code may have the same set of reasons to change.

Characteristics

  • A group of consecutive line-pairs that have the same duplication either located in one class or other parts of classes
  • A significant duplicated line of codes. For example, 1/3 of lines of code of the class.

Impact

Duplicated code can’t be avoided, and it can be evil to the system. In an ideal case, one class should offer one single responsibility for that functionality. If duplication appears to many other parts of code, can you imagine, how hard to locate the error even harder to refactor. The presence of code duplication makes twice harder to fix and refactor due to:

  • Bloating of the system where a lot of duplicated blocks of code
  • Evolution of cloning means cloning errors are increasing

Example

  • There are a few code duplications in several parts of a class

Guidelines

  • Same Class: Extract the commonalities in the form of a new method and call the new method from both places.
  • Siblings Classes: Extract the commonalities from both siblings classes and form a new method placed into parent class.