Yuval Adam Yuval Adam - 1 month ago 4
Java Question

Gracefully avoiding NullPointerException in Java

Consider this line:

if (object.getAttribute("someAttr").equals("true")) { // ....


Obviously this line is a potential bug, the attribute might be
null
and we will get a
NullPointerException
. So we need to refactor it to one of two choices:

First option:

if ("true".equals(object.getAttribute("someAttr"))) { // ....


Second option:

String attr = object.getAttribute("someAttr");
if (attr != null) {
if (attr.equals("true")) { // ....


The first option is awkward to read but more concise, while the second one is clear in intent, but verbose.

Which option do you prefer in terms of readability?

Answer

I've always used

if ("true".equals(object.getAttribute("someAttr"))) { // ....

because although it is a little more difficult to read it's much less verbose and I think it's readable enough so you get used to it very easily

Comments