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.
With Java 8 Optional : UserObj userObj=new UserObj(); Optional. ofNullable(fetchDetails()). ifPresent(var -> userObj.
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.
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."
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.
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 */);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With