Copy-paste programming is a common coding anti-pattern (and it's actually a trap). It describes the way developers repetitively copy and paste existing code (with further edit) instead of creating generalized solutions. Such a programming style often produces excessively large, unclear functions with many redundant code fragments. Such code is difficult to understand, and many repeated code fragments can blunt programmers' attention, which can cause typos. If the error was made initially, it will be reproduced many times through the code.
Such errors are quite frequent because it's almost impossible to avoid copying several lines in a row. For example, when we call a function with different (but similar in general) parameters and apply this function to different objects several times in a row. At the same time, manual code review is ineffective because the human eye may not notice a difference in just 1–2 characters.
It's better to automatically detect copy-paste errors on the code writing stage, for example, using the static analysis methodology. Unlike the common manual code review, its process is fully automated and covers the entire project code, including infrequently executed sections where errors may be difficult to detect using dynamic analysis methods.
Here are several examples of copy-paste errors in C++. They were found in popular open-source projects by the PVS-Studio static analyzer.
Fennec Media Project. Here is a typo in array items handling:
fhead[11] = '\0';
fhead[12] = '\0';
fhead[13] = '\0';
fhead[13] = '\0';
These four similar lines may have appeared in the program code because of copying. Then an error occurs during index editing that leads to zero being written twice to fhead[13] and not to fhead[14].
The ReactOS project. Here is the wrong object choice:
HPEN hhi = CreatePen(0, 0, MAKE_PALETTERGB(crHighlight));
HPEN hsh = CreatePen(0, 0, MAKE_PALETTERGB(crShadow));
....
if(fNormal)
hOld = SelectObject(hdc, hhi);
else
hOld = SelectObject(hdc, hhi);
....
The hsh object isn't used, but the hhi is always used.
Generally, the copy-paste programming can refer to the use or adaptation of existing third-party solutions, such as open-source software, without fully understanding their logic. This can lead to a project having a heterogeneous coding style, inefficient operation, and cluttered code.
References
0