Duplicate Code - Example of Functionally Duplicate Code

Example of Functionally Duplicate Code

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

extern int array1; extern int array2; int sum1 = 0; int sum2 = 0; int average1 = 0; int average2 = 0; for (int i = 0; i < 4; i++) { sum1 += array1; } average1 = sum1/4; for (int i = 0; i < 4; i++) { sum2 += array2; } average2 = sum2/4;

The two loops can be rewritten as the single function:

int calcAverage (int* Array_of_4) { int sum = 0; for (int i = 0; i < 4; i++) { sum += Array_of_4; } return sum/4; }

Using the above function will give source code that has no loop duplication:

extern int array1; extern int array2; int average1 = calcAverage(array1); int average2 = calcAverage(array2);

Read more about this topic:  Duplicate Code

Famous quotes containing the words duplicate and/or code:

    O Nature, and O soul of man! how far beyond all utterance are your linked analogies! not the smallest atom stirs or lives in matter, but has its cunning duplicate in mind.
    Herman Melville (1819–1891)

    ...I had grown up in a world that was dominated by immature age. Not by vigorous immaturity, but by immaturity that was old and tired and prudent, that loved ritual and rubric, and was utterly wanting in curiosity about the new and the strange. Its era has passed away, and the world it made has crumbled around us. Its finest creation, a code of manners, has been ridiculed and discarded.
    Ellen Glasgow (1873–1945)