Tags

Inner classes are better methods

October 2nd, 2006

A while ago a co-worker implemented an API and he found that there are many situation where he simply has to throw an exception. The exceptions had been all of this kind where you can not do anything about them, but nevertheless you have a lot of information to pass to the client that tell what was considered inconsistent.

He found himself repeating code and he refactored all the throws into a method that did nothing but the construction of the exception and throwed it.

So instead of

public int doSomething(String a){

if (a!=null) { return calc(a);}
else { throw new RuntimeException(”Argument must not be null!”);}

}

we had

public int doSomething(String a){

if (a!=null) { return calc(a);}
else { throwException();}

return -1; //Ugly ,but otherwise it fails to compile

}

But this does not compile without the bogus return, as the reachability analysis does not dive into methods like

final void throwException() {

throw new RuntimeException(”Argument must not be null!”);

}

The solution is simple and gives also easier to read code, but it uses inner-classes:

private class InnerException extends RuntimeException {

InnerException () {

super(”Argument must not be null!”);

}

so we get a happy compiler by writing

public void doSomething(String a){

if (a!=null) { return calc(a);}
else { throw new InnerException ();}

}

Now it is clear that an exception is thrown and as the inner classes ctor has the same access rights as a method, even more complex constructions of exceptions can be performed.

Interesting enough, this contradicts my Golden Rule 11

Note that the example is rather simplistic, the original throwException made access to different fields to prepare the error-analysis.