Replacing null check with java 8 optional
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 */);