'. '

EliminateFuzzyModifiers

From APIDesign

Revision as of 21:24, 25 March 2009 by JaroslavTulach (Talk | contribs)
Jump to: navigation, search

Fuzzy access modifiers are source of all evil as described at ClarityOfAccessModifiers page. Good message is that we do not need them. Our APIs can be clear enough with use of following easy steps.

Public Abstract

Imagine that there is a class with a single public abstract method like in this example:

Code from PublicAbstract.java:
See the whole file.

public abstract void increment();
 

This indeed violates the clarity rules and in many cases API designers may wish to eliminate it. The change is simple. Just split the method into two:

Code from PublicAbstract.java:
See the whole file.

public final void increment() {
    overridableIncrement();
}
protected abstract void overridableIncrement();
 

Now both methods use single meaning access modifiers, so the so wanted clarity is achieved. Moreover the usage of such API is made complex. Compare the original snippet with classical modifier:

Code from PublicAbstractTest.java:
See the whole file.

class DoubleIncrement extends PublicAbstract.Dirty {
    int counter;
 
    @Override
    public void increment() {
        counter += 2;
    }
}
DoubleIncrement doubleIncr = new DoubleIncrement();
doubleIncr.incrementTenTimes();
Assert.assertEquals(20, doubleIncr.counter);
 

With the same code rewritten to clean version with two methods. Everything remains the same, just instead of overriding the final method, one needs to override the protected abstract one:

Code from PublicAbstractTest.java:
See the whole file.

class DoubleIncrement extends PublicAbstract.Clean {
    int counter;
 
    @Override
    protected void overridableIncrement() {
        counter += 2;
    }
}
DoubleIncrement doubleIncr = new DoubleIncrement();
doubleIncr.incrementTenTimes();
Assert.assertEquals(20, doubleIncr.counter);
 

Eliminiating public abstract modifiers is easy, if found desirable.

TBD: Meanwhile see the book's Chapter 10, Cooperating with Other APIs where this topic is discussed.

buy