Code Smell – Bad Smell in Code :: Duplicate code
Repeatation is the root of software evil.
Every time you see duplication in the code, it represents a missed opportunity for abstraction. That duplication could probably become a subroutine or perhaps another class outright.
By folding the duplication into such an abstraction, you increase the vocabulary of the language of your design. Other programmers can use the abstract facilities you create. Coding becomes faster and less error prone because you have raised the abstraction level.
The most obvious form of duplication is when you have clumps of identical code that look like some programmers went wild with the mouse, pasting the same code over and over again. These should be replaced with simple methods.
A more subtle form is the switch/case or if/else chain that appears again and again in various modules, always testing for the same set of conditions. These should be replaced with polymorphism.
Still more subtle are the modules that have similar algorithms, but that don’t share similar lines of code.
Note: Find and eliminate duplication wherever you can.
Duplication_of_code.java
public class Duplication_of_code
{
public void method()
{
int x = getValue();
if(x > 10)
{ // Violation.
int j = i + 20;
int k = j * 5;
System.out.print(k);
}
else if( x < 20 )
{ // Violation.
int j = i + 20;
int k = j * 5;
System.out.print(k);
}
}
}
Recent Comments