In computer programming, duplicate code is multiple occurrences of equivalent source code in a codebase. A duplicate code fragment is also known as a code clone, and the process of finding clones in source code is called clone detection. Duplicate code has multiple Code smell aspects.
Whether fragments are classified as duplicate can be subjective. Fragments that are very small such as a single statement are probably not classified as duplicate. Additionally, fragments that are not exactly the same text might be considered duplicate code if they match except for less important aspects such as whitespace, comments and variable names. Even fragments that are only functionally equivalent may be classified as duplicate.
However, not all code duplication can be refactored. Clones may be the most effective solution if the programming language provides inadequate or overly complex abstractions, particularly if supported with user interface techniques such as simultaneous editing. Furthermore, the risk of breaking code when refactoring may outweigh maintenance benefit.Kapser, C.; Godfrey, M.W., ""Cloning Considered Harmful" Considered Harmful," 13th Working Conference on Reverse Engineering (WCRE), pp. 19-28, Oct. 2006 A study by Wagner, Abdulkhaleq, and Kaya concluded that while additional work must be done to keep duplicates in sync, if the programmers involved are aware of the duplicate code there weren't significantly more faults caused than in unduplicated code.
Another cost is memory size as duplicate code requires memory to store each copy.
For example, the following code calculates the average of an array of .
int sum_a = 0;
for (int i = 0; i < 4; i++) {
int average_a = sum_a / 4;
int sum_b = 0;
for (int i = 0; i < 4; i++) {
int average_b = sum_b / 4;
sum_a += array_a[i];
}
sum_b += array_b[i];
}
The two loops can be rewritten as the function:
int sum = 0;
for (int i = 0; i < 4; i++) {
sum += a[i];
}
return sum / 4;
}
Using this function eliminates the duplicated code.
int average1 = calc_average_of_four(array1);
int average2 = calc_average_of_four(array2);
The compiler might inline the calls such that the resulting machine code is identical for both versions. If the function is not inlined, then the additional overhead of the function calls will take longer to run by a relatively small amount.
|
|