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)

    Many people will say to working mothers, in effect, “I don’t think you can have it all.” The phrase for “have it all” is code for “have your cake and eat it too.” What these people really mean is that achievement in the workplace has always come at a price—usually a significant personal price; conversely, women who stayed home with their children were seen as having sacrificed a great deal of their own ambition for their families.
    Anne C. Weisberg (20th century)