Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gracefully avoiding NullPointerException in Java

Tags:

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?

like image 448
Yuval Adam Avatar asked Jun 08 '09 08:06

Yuval Adam


People also ask

What can help us in avoiding NullPointerException?

Java 8 introduced an Optional class which is a nicer way to avoid NullPointerExceptions. You can use Optional to encapsulate the potential null values and pass or return it safely without worrying about the exception. Without Optional, when a method signature has return type of certain object.

How do you stop NullPointerException in Java?

How to avoid the NullPointerException? To avoid the NullPointerException, we must ensure that all the objects are initialized properly, before you use them. When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects.

Is it good practice to throw NullPointerException?

It is generally a bad practice to catch NullPointerException.

How do I stop null check?

Avoiding Null Checks Through Coding Practices It's usually a good practice to write code that fails early. So, if an API accepts multiple parameters that aren't allowed to be null, it's better to check for every non-null parameter as a precondition of the API.


2 Answers

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

like image 102
victor hugo Avatar answered Sep 29 '22 10:09

victor hugo


In the second option, you can take advantage of short-circuiting &&:

String attr = object.getAttribute("someAttr"); if (attr != null && attr.equals("true")) { // .... 
like image 40
laalto Avatar answered Sep 29 '22 11:09

laalto