Gracefully avoiding NullPointerException in Java

Posted by Yuval A on Stack Overflow See other posts from Stack Overflow or by Yuval A
Published on 2009-06-08T08:48:36Z Indexed on 2010/04/04 9:13 UTC
Read the original article Hit count: 314

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about code-readability