In
computer programming
Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, duplicate code is a sequence of
source code
In computing, source code, or simply code or source, is a plain text computer program written in a programming language. A programmer writes the human readable source code to control the behavior of a computer.
Since a computer, at base, only ...
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. 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, the automated process of finding duplications in source code is called clone detection.
Two code sequences may be duplicates of each other without being character-for-character identical, for example by being character-for-character identical only when white space characters and comments are ignored, or by being
token-for-token identical, or token-for-token identical with occasional variation. Even code sequences that are only functionally identical may be considered duplicate code.
Emergence
Some of the ways in which duplicate code may be created are:
*
copy and paste programming, which in academic settings may be done as part of
plagiarism
Plagiarism is the representation of another person's language, thoughts, ideas, or expressions as one's own original work.From the 1995 ''Random House Dictionary of the English Language, Random House Compact Unabridged Dictionary'': use or close ...
* scrounging, in which a section of code is copied "because it works". In most cases this operation involves slight modifications in the cloned code, such as renaming variables or inserting/deleting code. The language nearly always allows one to call one copy of the code from different places, so that it can serve multiple purposes, but instead the programmer creates another copy, perhaps because they
** do not understand the language properly
** do not have the time to do it properly, or
** do not care about the increased
active software rot.
It may also happen that functionality is required that is very similar to that in another part of a program, and a developer independently writes code that is very similar to what exists elsewhere. Studies suggest that such independently rewritten code is typically not syntactically similar.
Automatically generated code, where having duplicate code may be desired to increase speed or ease of development, is another reason for duplication. Note that the actual generator will not contain duplicates in its source code, only the output it produces.
Fixing
Duplicate code is most commonly fixed by moving the code into its own unit (
function or module) and calling that unit from all of the places where it was originally used. Using a more open-source style of development, in which components are in centralized locations, may also help with duplication.
Costs and benefits
Code which includes duplicate functionality is more difficult to support because,
* it is simply longer, and
* if it needs updating, there is a danger that one copy of the code will be updated without further checking for the presence of other instances of the same code.
On the other hand, if one copy of the code is being used for different purposes, and it is not properly documented, there is a danger that it will be updated for one purpose, but this update will not be required or appropriate to its other purposes.
These considerations are not relevant for automatically generated code, if there is just one copy of the functionality in the source code.
In the past, when memory space was more limited, duplicate code had the additional disadvantage of taking up more space, but nowadays this is unlikely to be an issue.
When code with a
software vulnerability
Vulnerabilities are flaws or weaknesses in a system's design, implementation, or management that can be exploited by a malicious actor to compromise its security.
Despite a system administrator's best efforts to achieve complete correctness, vir ...
is copied, the vulnerability may continue to exist in the copied code if the developer is not aware of such copies.
Refactoring
In computer programming and software design, code refactoring is the process of restructuring existing source code—changing the '' factoring''—without changing its external behavior. Refactoring is intended to improve the design, structure, ...
duplicate code can improve many software metrics, such as
lines of code,
cyclomatic complexity, and
coupling. This may lead to shorter compilation times, lower
cognitive load
In cognitive psychology, cognitive load is the effort being used in the working memory. According to work conducted in the field of instructional design and pedagogy, broadly, there are three types of cognitive load:
* ''Intrinsic'' cognitive load ...
, less
human error
Human error is an action that has been done but that was "not intended by the actor; not desired by a set of rules or an external observer; or that led the task or system outside its acceptable limits".Senders, J.W. and Moray, N.P. (1991) Human Er ...
, and fewer forgotten or overlooked pieces of code. 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 risks of breaking code when refactoring may outweigh any maintenance benefits.
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.
Detecting duplicate code
A number of different algorithms have been proposed to detect duplicate code. For example:
*
Baker
A baker is a tradesperson who baking, bakes and sometimes Sales, sells breads and other products made of flour by using an oven or other concentrated heat source. The place where a baker works is called a bakery.
History
Ancient histo ...
's algorithm.
*
Rabin–Karp string search algorithm.
* Using
abstract syntax trees.
* Visual clone detection.
* Count matrix clone detection.
*
Locality-sensitive hashing
*
Anti-unification[Bulychev, Peter, and Marius Minea.]
Duplicate code detection using anti-unification
" Proceedings of the Spring/Summer Young Researchers’ Colloquium on Software Engineering. No. 2. Федеральное государственное бюджетное учреждение науки Институт системного программирования Российской академии наук, 2008.
Example of functionally duplicate code
Consider the following
code snippet for calculating the
average
In colloquial, ordinary language, an average is a single number or value that best represents a set of data. The type of average taken as most typically representative of a list of numbers is the arithmetic mean the sum of the numbers divided by ...
of an
array of
integer
An integer is the number zero (0), a positive natural number (1, 2, 3, ...), or the negation of a positive natural number (−1, −2, −3, ...). The negations or additive inverses of the positive natural numbers are referred to as negative in ...
s
extern int array_a[];
extern int array_b[];
int sum_a = 0;
for (int i = 0; i < 4; i++)
sum_a += array_a[i];
int average_a = sum_a / 4;
int sum_b = 0;
for (int i = 0; i < 4; i++)
sum_b += array_b[i];
int average_b = sum_b / 4;
The two loops can be rewritten as the single function:
int calc_average_of_four(int* array)
or, usually preferably, by parameterising the number of elements in the array.
Using the above function will give source code that has no loop duplication:
extern int array1[];
extern int array2[];
int average1 = calc_average_of_four(array1);
int average2 = calc_average_of_four(array2);
Note that in this trivial case, the compiler may choose to inline expansion, inline both calls to the function, such that the resulting machine code is identical for both the duplicated and non-duplicated examples above. If the function is not inlined, then the
Subroutine#Disadvantages, additional overhead of the function calls will probably take longer to run (on the order of 10 processor instructions for most high-performance languages). Theoretically, this additional time to run could matter.
See also
*
Abstraction principle (programming) In software engineering and programming language theory, the abstraction principle (or the principle of abstraction) is a basic dictum that aims to reduce duplication of information in a program (usually with emphasis on code duplication) whenever p ...
*
Anti-pattern
An anti-pattern in software engineering, project management, and business processes is a common response to a recurring problem that is usually ineffective and risks being highly counterproductive. The term, coined in 1995 by computer programmer An ...
*
Data deduplication
In computing, data deduplication is a technique for eliminating duplicate copies of repeating data. Successful implementation of the technique can improve storage utilization, which may in turn lower capital expenditure by reducing the overall amou ...
*
Don't repeat yourself
"Don't repeat yourself" (DRY) is a principle of software development aimed at reducing repetition of information which is likely to change, replacing it with abstractions that are less likely to change, or using data normalization which avoids r ...
(DRY)
*
List of tools for static code analysis
*
Redundant code
*
Rule of three (computer programming)
References
{{reflist
External links
The University of Alabama at Birmingham: Code Clones LiteratureFinding duplicate code in C#, VB.Net, ASPX, Ruby, Python, Java, C, C++, ActionScript, or XAML
Articles with example C code
Software metrics
Source code