I have just stumbled across a piece of code like this:
Object getSomeValue() { Object value = null; try { value = errorProneOperation(); } catch (IOException e) { throw new IllegalStateException(e); } return value; }
Now I find this really awkward. Why initialise something to null to keep the compiler happy?
Surely you want to do this:
Object getSomeValue() { try { Object value = errorProneOperation(); return value; } catch (IOException e) { throw new IllegalStateException(e); } }
No useless initialisation here. Also the scope of the local variable is smaller, which is good. I think there is a general rule here, which is: “There should be nothing after your catch-handler apart from a potential finally”. As with all rules it might be broken, but only with good reason. I don’t want to see that crappy initialisation to null again.
Leave a Reply