Saturday, November 22, 2014

Opening and closing resources

It's the silliest thing that's been bothering me for agest: why on earth would someone go through all the trouble to write code like that:

InputStream in = null;
try {
    in = openInputStream();
    // do something with in
} finally {
    if (in != null) {
        in.close();
    }
}

First of all, if opening a stream didn't succeed then an exception is thrown and "in" is going to be as null as it gets - that's true, but the actual exception is going to get propagated upwards too - so why the hell do the it in the try block and check for null in finally? It's just so pointless I can't stand it..

InputStream in = openInputStream();
try {
    // do something with in
} finally {
    in.close();
}

Now isn't that a lot more readable, simpler and everything? If the opening of a stream blows up everything blows up too - just like in the code above.

Can anyone please be kind and explain this complete insanity to me?

Sure, with Java 7 we have the try-with-resources feature - but is it doing anything more than the second form?

try (InputStream in = openInputStream()) {
    // do something with in
}

The visibility of the stream is limited to the body of the try statement which seems to be the absolutely only difference to the previous version (the pre-java7 one).

No comments: