Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing null check with java 8 optional

I am trying to replace below code block with optional, just want to check will there be any bad implications of doing this like performance or anything as such?

Existing code:

UserObj userObj=new UserObj();
Object result = fetchDetails();
if (null != result) {
    userObj.setResult(result.toString());
}

With Java 8 Optional:

UserObj userObj=new UserObj();
Optional.ofNullable(fetchDetails()).ifPresent(var -> userObj.setResult(var.toString()));

Doing this change just to make code look concise as there are lot of null check blocks in my code.

like image 228
springenthusiast Avatar asked Jan 29 '19 08:01

springenthusiast


People also ask

How do you replace an Optional null check in Java 8?

With Java 8 Optional : UserObj userObj=new UserObj(); Optional. ofNullable(fetchDetails()). ifPresent(var -> userObj.

What is the difference between Optional and null check in Java 8?

In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional class forces you to think about the case when the value is not present.

How do I return Optional instead of null?

In Java 8 you can return an Optional instead of a null . Java 8 documentation says that an Optional is "A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value."

How do you do null check for Optional in Java?

Optional was introduced to Java as a way to fix the issues with null references. Before Optional , every object was allowed to either contain a value or not (i.e. being null ). The introduction of Optional essentially enforces null -checking by the type-system making it unnecessary to perform such checks manually.


1 Answers

First of all I think you're misunderstanding the purpose of Optional. It is not just for replacing

if(obj != null){ ... }

The main point of Optional is to provide a means for a function returning a value to indicate the absence of a return value. Please read this post for more details.

The proper use of Optional in your case would be returning optional ResultObj from fetchDetails method:

Optional<ResultObj> fetchDetails() {
   ...
}

Then you simply chain the methods on fetched Optional as you did before.

Update

In case you cannot modify fetchDetails there is still an option of wrapping it into your own method like the following:

Optional<ResultObj> fetchOptionalDetails() {
    return Optional.ofNullable(fetchDefails());
}

Creating a new method will add a tiny overhead, but the code will be much more readable:

fetchOptionalDetails().ifPresent(details -> /* do something */);
like image 77
ETO Avatar answered Oct 31 '22 18:10

ETO