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:

    A man’s desire for a son is usually nothing but the wish to duplicate himself in order that such a remarkable pattern may not be lost to the world.
    Helen Rowland (1875–1950)

    Acknowledge your will and speak to us all, “This alone is what I will to be!” Hang your own penal code up above you: we want to be its enforcers!
    Friedrich Nietzsche (1844–1900)