This is believed to be the worst code smell. In the case of a bug or a new feature, all duplicate instances in the source code have to be found and updated. Inconsistent updates may lead to errors.
Clone Detection
- Type 1: Code fragments are identical except for variations in white space, layout and commends
- Why are some clones not refactorable?
- The clones return more than one variable
- The clones return variables with different types
- The clones contain conditional return statements
- The clones contain branching statements without corresponding loops
- Why are some clones not refactorable?
- Type 2: Code fragments are structurally and syntactically identical except for variables in identifiers, literals, type, in addition to Type 1 differences
- You can make generic types out of these
- Type 3: Code fragments are copies with further modifications. Statements can be changed, added, or removed in addition to Type 2 differences
- Type 4: Two or more code fragments perform the same computation but are implement with syntactic differences
- Ex. Different sorting algorithms
Refactoring
- If the duplicate code is in the same class, apply extract method refactoring
- If the duplicate code is in a different sub class of the same super class, apply extract and pull up method refactoring
- If the duplicate code is in different unrelated classes, make a common super class (new) or a utility class