'. '

AlternativeBehavior

From APIDesign

Revision as of 08:19, 8 November 2010 by JaroslavTulach (Talk | contribs)
(diff) ←Older revision | Current revision (diff) | Newer revision→ (diff)
Jump to: navigation, search

As has been explained in ClarityOfAccessModifiers page, sometimes even relatively fine looking API can have a hidden catch. Just like following Arithmetica class:

Code from Arithmetica.java:
See the whole file.

public class Arithmetica {
    public int sumTwo(int one, int second) {
        return one + second;
    }
 
    public int sumAll(int... numbers) {
        if (numbers.length == 0) {
            return 0;
        }
        int sum = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            sum = sumTwo(sum, numbers[i]);
        }
        return sum;
    }
 
    public int sumRange(int from, int to) {
        int len = to - from;
        if (len < 0) {
            len = -len;
            from = to;
        }
        int[] array = new int[len + 1];
        for (int i = 0; i <= len; i++) {
            array[i] = from + i;
        }
        return sumAll(array);
    }
}
 

Without getting into details (more in ClarityOfAccessModifiers), let's assume the problem is clear and that we all understand that releasing version 2.0 of that class with following reimplementation of the sumRange method would clearly be an incompatible API change:

Code from Arithmetica.java:
See the whole file.

public int sumRange(int from, int to) {
    return (from + to) * (Math.abs(to - from) + 1) / 2;
}
 

As the whole API Design methodology advocates as little of incompatible changes as possible, it shall be clear that we have a problem. What can we do? Is all our API development in stuck? Do we need to keep the old, slow 1.0 version of sumRange method? Do we have to sacrifice BackwardCompatibility? No and no. We just need to learn how to provide AlternativeBehaviours.

Contents