Duplicate code

In computer programming, duplicate code is a sequence of source code 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.[1] 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:

  • 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.[2]

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 is copied, the vulnerability may continue to exist in the copied code if the developer is not aware of such copies.[3] Refactoring 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, less human error, and fewer forgotten or overlooked pieces of code. However, not all code duplication can be refactored.[4] 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. [5] 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. [6][disputeddiscuss]

Detecting duplicate code

A number of different algorithms have been proposed to detect duplicate code. For example:

Example of functionally duplicate code

Consider the following code snippet for calculating the average of an array of integers

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) {
   int sum = 0;
   for (int i = 0; i < 4; i++)
       sum += array[i];

   return sum / 4;
}

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 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 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.

Example of duplicate code fix via code replaced by the method

See also

References

  1. ^ Spinellis, Diomidis. "The Bad Code Spotter's Guide". InformIT.com. Retrieved 2008-06-06.
  2. ^ Code similarities beyond copy & paste by Elmar Juergens, Florian Deissenboeck, Benjamin Hummel.
  3. ^ Li, Hongzhe; Kwon, Hyuckmin; Kwon, Jonghoon; Lee, Heejo (25 April 2016). "CLORIFI: software vulnerability discovery using code clone verification". Concurrency and Computation: Practice and Experience. 28 (6): 1900–1917. doi:10.1002/cpe.3532. S2CID 17363758.
  4. ^ Arcelli Fontana, Francesca; Zanoni, Marco; Ranchetti, Andrea; Ranchetti, Davide (2013). "Software Clone Detection and Refactoring" (PDF). ISRN Software Engineering. 2013: 1–8. doi:10.1155/2013/129437.
  5. ^ Kapser, C.; Godfrey, M.W., ""Cloning Considered Harmful" Considered Harmful," 13th Working Conference on Reverse Engineering (WCRE), pp. 19-28, Oct. 2006
  6. ^ Wagner, Stefan; Abdulkhaleq, Asim; Kaya, Kamer; Paar, Alexander (2016). "On the Relationship of Inconsistent Software Clones and Faults: An Empirical Study". 2016 IEEE 23rd International Conference on Software Analysis, Evolution, and Reengineering (SANER). pp. 79–89. arXiv:1611.08005. doi:10.1109/SANER.2016.94. ISBN 978-1-5090-1855-0. S2CID 3154845.
  7. ^ Brenda S. Baker. A Program for Identifying Duplicated Code. Computing Science and Statistics, 24:49–57, 1992.
  8. ^ Ira D. Baxter, et al. Clone Detection Using Abstract Syntax Trees
  9. ^ Visual Detection of Duplicated Code Archived 2006-06-29 at the Wayback Machine by Matthias Rieger, Stephane Ducasse.
  10. ^ Yuan, Y. and Guo, Y. CMCD: Count Matrix Based Code Clone Detection, in 2011 18th Asia-Pacific Software Engineering Conference. IEEE, Dec. 2011, pp. 250–257.
  11. ^ Chen, X., Wang, A. Y., & Tempero, E. D. (2014). A Replication and Reproduction of Code Clone Detection Studies. In ACSC (pp. 105-114).
  12. ^ 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.

Read other articles:

Lihat pula: Daftar pemilihan umum kepala daerah di Indonesia 2010 Pemilihan Umum Bupati Pandeglang 2010200520153 Oktober 2010 (putaran pertama)26 Desember 2010 (putaran kedua)Terdaftar813,185 jiwaKehadiran pemilih546,270 (67.17%)(putaran kedua)Kandidat   Calon Erwan Kurtubi Irna Narulita Yoyon Sudjana Partai Partai Golongan Karya PPP Independen Pendamping Heryani Apud Mahpud Muhamad Oyim Suara rakyat 265,263 220,624 22,003 Persentase 49.62% 41.27% 4.12%   Calon Edi Suhaedi Suna...

 

 

1986 video gameDraculaPublisher(s)CRL GroupDesigner(s)Rod PikeIan ElleryPlatform(s)Amstrad CPC, Commodore 64, ZX SpectrumRelease1986Genre(s)Interactive fictionMode(s)Single-player Dracula is a text adventure game by CRL released in 1986 for the Commodore 64, Amstrad CPC, and ZX Spectrum home computers. The game is based on the novel Dracula by Bram Stoker. It was the first video game to be rated by the BBFC. The game received a 15 certificate.[1] Plot An English lawyer travels to Car...

 

 

2020 United States House of Representatives elections in Mississippi ← 2018 November 3, 2020 (2020-11-03) 2022 → All 4 Mississippi seats to the United States House of Representatives   Majority party Minority party   Party Republican Democratic Last election 3 1 Seats won 3 1 Seat change Popular vote 806,859 421,121 Percentage 65.71% 34.29% Swing 15.53% 8.18% Republican   60–70%   90>% Democratic ...

Questa voce sugli argomenti drammaturghi e scrittori australiani è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Thomas Michael Keneally Thomas Michael Keneally (Sydney, 7 ottobre 1935) è uno scrittore, drammaturgo e attore australiano, noto per aver scritto il romanzo La lista di Schindler. Successivamente riadattato per il cinema per il film Premio Oscar Schindler's List - La lista di Schindler di Steven Spielberg, il romanzo ha vinto il Booker Pri...

 

 

Regency in South Sulawesi, IndonesiaPangkajene & Islands Regency Kabupaten Pangkajene dan KepulauanRegency Coat of armsLocation within South SulawesiPangkajene & Islands RegencyShow map of SulawesiPangkajene & Islands RegencyShow map of IndonesiaCoordinates: 4°45′S 119°30′E / 4.750°S 119.500°E / -4.750; 119.500Country IndonesiaProvince South SulawesiCapitalPangkajeneArea • Total1,112.29 km2 (429.46 sq mi)Population (m...

 

 

Georgina Beyer was the first openly transgender mayor and Member of Parliament in the world This is a list of LGBTQIA+ (lesbian, gay, bisexual, transgender and intersex) holders of political offices in New Zealand. Charles Mackay, who served as Mayor of Whanganui for a non-consecutive period from 1906 to 1920, is the first known gay mayor. Mackay resigned from his position in 1920 after the attempted murder of poet D'Arcy Cresswell, who allegedly blackmailed him and threatened to publicly ex...

Hentaigana (変体仮名code: ja is deprecated ) adalah salah satu variasi bentuk hiragana, dan dipakai di Jepang hingga dikeluarkannya revisi peraturan pemerintah tentang sekolah dasar pada tahun 1900. Setelah dibakukannya bentuk hiragana, penggunaan hentaigana hanya terbatas pada papan reklame dan kaligrafi.[1] Nama lain untuk hentaigana adalah itaigana (異体仮名code: ja is deprecated , bentuk karakter yang tidak baku).[2] Contoh hentaigana 以 (い, i) 江 (え, e) 於 ...

 

 

Seo Ji-sooLahirSeo Ji-soo11 Februari 1994 (umur 30)Incheon, Korea SelatanPekerjaanPenyanyiAktrisKarier musikGenreK-popInstrumenVokalTahun aktif2014–sekarangLabelWoollimArtis terkaitLovelyz Seo Ji-soo (서지수)[1] (lahir 11 Februari 1994) adalah seorang penyanyi dan rapper asal Korea Selatan. Ia adalah anggota grup vokal perempuan Lovelyz, yang debut pada 2014 di bawah naungan Woollim Entertainment. Karena rumor yang berkembang sepekan sebelum debut resmi grup tersebut, Ji-so...

 

 

イスラームにおける結婚(イスラームにおけるけっこん)とは、二者の間で行われる法的な契約である。新郎新婦は自身の自由な意思で結婚に同意する。口頭または紙面での規則に従った拘束的な契約は、イスラームの結婚で不可欠だと考えられており、新郎と新婦の権利と責任の概要を示している[1]。イスラームにおける離婚は様々な形をとることができ、個�...

Tournoi olympique de handballSydney 2000 Généralités Sport Handball Édition Hommes : 8e[1], Femmes : 7e Lieu(x) parc olympique, Sydney, Australie Date Du 16 septembre 2000 au 1er octobre 2000 Participants 22 équipes(12 masc. et 10 fém.) Épreuves 2 Palmarès Tenant du titre Hommes : CroatieFemmes : Danemark Vainqueur Hommes : RussieFemmes : Danemark Finaliste Hommes : SuèdeFemmes : Hongrie Troisième Hommes : EspagneFemmes : Norvège N...

 

 

Stately home in North Yorkshire, England Castle HowardSouth (garden) face of Castle HowardTypeStately homeLocationNorth Yorkshire, EnglandCoordinates54°7′17″N 0°54′21″W / 54.12139°N 0.90583°W / 54.12139; -0.90583OS grid referenceSE 71635 70088Built1701–1811ArchitectsJohn Vanbrugh and Nicholas HawksmoorArchitectural style(s)English BaroqueOwnerCastle Howard Estate Limited[1]Websitecastlehoward.co.uk Listed Building – Grade IOfficial nameCastle Ho...

 

 

Species of bird Black-sided robin Illustration by J. G. Keulemans, c. 1894 Conservation status Least Concern  (IUCN 3.1)[1] Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Chordata Class: Aves Order: Passeriformes Infraorder: Passerides Family: Petroicidae Genus: Poecilodryas Species: P. hypoleuca Binomial name Poecilodryas hypoleuca(G. R. Gray, 1859) The black-sided robin (Poecilodryas hypoleuca), also known as the pied robin, is a species of bird in t...

Howard Cosell Información personalNombre de nacimiento Howard William Cohen Nombre en inglés Howard William Cosell Nacimiento 25 de marzo de 1918 Winston-Salem (Estados Unidos) Fallecimiento 23 de abril de 1995 (77 años)Manhattan (Estados Unidos) Causa de muerte Insuficiencia cardíaca Sepultura Westhampton Cemetery Nacionalidad EstadounidenseFamiliaHijos 2 EducaciónEducado en Escuela de Derecho de la Universidad de Nueva YorkUniversidad de Nueva YorkAlexander Hamilton High SchoolBoys Hig...

 

 

This biography of a living person needs additional citations for verification. Please help by adding reliable sources. Contentious material about living persons that is unsourced or poorly sourced must be removed immediately from the article and its talk page, especially if potentially libelous.Find sources: Celebrity Big Brother (British TV series) series 19 – news · newspapers · books · scholar · JSTOR (February 2020) (Learn how and when to remove th...

 

 

2020年夏季奥林匹克运动会波兰代表團波兰国旗IOC編碼POLNOC波蘭奧林匹克委員會網站olimpijski.pl(英文)(波兰文)2020年夏季奥林匹克运动会(東京)2021年7月23日至8月8日(受2019冠状病毒病疫情影响推迟,但仍保留原定名称)運動員206參賽項目24个大项旗手开幕式:帕维尔·科热尼奥夫斯基(游泳)和马娅·沃什乔夫斯卡(自行车)[1]闭幕式:卡罗利娜·纳亚(皮划艇)&#...

2014 Uruguayan general election ← 2009 26 October 2014 (first round)30 November 2014 (second round) 2019 → Registered2,620,791Turnout90.51% (first round) 0.60pp88.58% (second round) 0.60pp Presidential election   Nominee Tabaré Vázquez Luis Lacalle Pou Party Broad Front National Party Running mate Raúl Sendic Jorge Larrañaga Popular vote 1,241,568 955,741 Percentage 56.50% 43.50% President before election José Mujica Broad Front Elected President Tab...

 

 

Sir Thomas More wearing the Collar of Esses as Lord Chancellor, by Hans Holbein the Younger (1527). In jewelry, a collar is an ornament for the neck. Collar is an older word for necklace, and is usually reserved today for a necklace that lies flat to the body rather than hanging freely and rests directly above the collar bone. In contemporary fine jewelry, collar necklaces are 14 inches in chain length and look similar to a collar on a shirt. In street fashion, collars are more commonly refer...

 

 

Bohemia Kingdom of Bohemia České království (لغة تشيكية)Königreich Böhmen (لغة ألمانية)Regnum Bohemiae (لغة لاتينية) الأمير الناخب جزء من ملكية هابسبورغ (1620/27–1804) الإمبراطورية النمساوية (1804–67)جزء من سيسليثانيا في النمسا-المجر (1867–1918) تابع 1198 – 1918 مملكة بوهيمياعلم مملكة بوهيمياشعار مملكة بوهيميا 1618 ...

Irish Gaelic footballer Niall MorganPersonal informationSport Gaelic footballPosition GoalkeeperBorn (1991-07-17) 17 July 1991 (age 32)Dungannon, Northern IrelandHeight 1.84 m (6 ft 0 in)Club(s)Years Club Edendork St Malachy'sInter-county(ies)Years County2013– TyroneInter-county titlesUlster titles 3All-Irelands 1 Association football careerDate of birth (1991-07-17) 17 July 1991 (age 32)Place of birth Dungannon, Northern IrelandHeight 1.84 m (6 ft 0 ...

 

 

Overview of the role of the Confederate state of Georgia during the American Civil War This article is about the Confederate state of Georgia between 1861 and 1865. For the ships, see CSS Georgia. For other uses, see Georgia (disambiguation). Georgia Variant flag (de facto)[FN 1]Seal (1863–1865) Map of the Confederate StatesCapitalMilledgevilleLargest citySavannahAdmitted to the ConfederacyMarch 16, 1861 (2nd)Population1,082,757 total • 620,527 (57.31%) free •...