This is an AMP version of the article, its original content can be found here.
Try. Finally. If. Not. Null.
There is a very typical mistake in pre-Java7 "try/finally" scenario,
which I keep seeing in so many code reviews. I just have to write about it.
Java7 introduced a solution, but it doesn't cover all situations.
Sometimes we need to deal with non-
AutoCloseable resources. Let's
open and close them correctly, please.
This is how it looks (assuming we are in Java 6):
I already wrote about
and its evil nature. Here it comes again. If you just follow the rule
of "not using NULL anywhere ever," this code would need an immediate
refactoring. Its correct version will look like this:
There is no
null anymore and it's very clean. Isn't it?
There are situations when opening the resource itself throws
and we can't put it outside of
try/catch. In that case, we have to have
But there should be no
The presence of
null in Java code is a clear indicator of code smell. Something
is not right if you have to use
null. The only place where the presence of
is justified is where we're using third-party APIs or JDK. They may return
null sometimes because... well, their design is bad. We have
no other option but to do
if(x==null). But that's it. No other places
are good for