Enrico Ceron Enrico Ceron - 6 months ago 10
Java Question

Java re-engineering of two classes

It is asked to re-engineering this two Java classes in order to avoid code duplication and improve maintainability.

public class Adder {
public int sum(int[] array) {
int result = 0;
for (int i = 0; i < array.length; i++) {
result += array[i];
}
return result;
}

public class Multiplier {
public int multiply(int[] array) {
int result = 1;
for (int i = 0; i < array.length; i++) {
result *= array[i];
}
return result;
}


Pay attention to different
result
initialization; it's my main problem.

Answer

I`d like to post my answer in spite of the question already having a good answer(I was too slow). The point in my solution is that is open for new Operations, you don't have to know different function names(so you can i.e. inject ArrayFunction into other classes):

public abstract class ArrayFuntion {

    public int compute(int[] array) {
        int result = initResult();
        for (int i = 0; i < array.length; i++) {
            result = compute(result, array[i]);
        }
        return result;
    }

    protected abstract int compute(int result, int i);

    protected abstract int initResult();

}


public class Adder extends ArrayFuntion{

    @Override
    protected int compute(int result, int arrayItem) {
        return result + arrayItem;
    }

    @Override
    protected int initResult() {
        return 0;
    }

}


public class Multiplier extends ArrayFuntion {

    @Override
    protected int compute(int result, int arrayItem) {
        return result * arrayItem;
    }

    @Override
    protected int initResult() {
        return 1;
    }

}
Comments