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.
解决方案
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 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 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 */);