ClarityOfAccessModifiers
From APIDesign
JaroslavTulach (Talk | contribs)
(New page: An important aspect of any API is its Clarity. As API is about communication between the API writer and API user, the Clarity here needs to be applied to the commun...)
Next diff →
Revision as of 09:00, 16 February 2009
An important aspect of any API is its Clarity. As API is about communication between the API writer and API user, the Clarity here needs to be applied to the communication. If the communication is clear, if the intention of the API writer correctly re-emerges in API users' heads then the API is clear enough.
Easy, one might thing. However expressing yourself clearly in some language requires deep understanding of meaning of its words, sentences and other language constructs. This is true for English as well as Java. For example guess what the following API can be useful for:
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); } }
Is this class useful only for summing up two numbers, few numbers and a range? Not at all! With a little bit of invention one can sufficiently use it to compute factorial:
Code from Factorial.java:
See the whole file.public final class Factorial extends Arithmetica { public static int factorial(int n) { return new Factorial().sumRange(1, n); } @Override public int sumTwo(int one, int second) { return one * second; } }
At first this might look as perfect example of object oriented reuse, however if you are a maintainer of such API and you want to provide new enhanced version, this can easily lead to BackwardCompatibility nightmare (as described in AlternativeBehaviours).
Fuzzy Access Modifiers
What is cause of the problem? The problem is that in the world of API design access modifiers have different meaning than one could originally thought.
public/abstract/final protected/abstract/final
Using modifiers with more than single meaning significantly hurts Clarity. What a user of an API is supposed to think when there is a protected method? Is it something that shall be called or something that shall be overriden and implemented?
TBD