Gracefully avoiding NullPointerException in Java
- by Yuval A
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?