用Java 8可选替换null检查 [英] 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?
现有代码:
UserObj userObj=new UserObj();
Object result = fetchDetails();
if (null != result) {
userObj.setResult(result.toString());
}
使用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.
推荐答案
首先,我认为您误解了Optional
的目的.不仅仅是替换
First of all I think you're misunderstanding the purpose of Optional
. It is not just for replacing
if(obj != null){ ... }
Optional
的要点是为函数返回值提供一种手段,以指示不存在返回值.请阅读这篇文章以了解更多详细信息.
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.
在您的情况下正确使用Optional
将会从fetchDetails
方法返回可选的ResultObj
:
The proper use of Optional
in your case would be returning optional ResultObj
from fetchDetails
method:
Optional<ResultObj> fetchDetails() {
...
}
然后,您只需像以前一样简单地将方法链接在获取的Optional
上即可.
Then you simply chain the methods on fetched Optional
as you did before.
更新
如果您无法修改fetchDetails
,仍然可以选择将其包装到您自己的方法中,如下所示:
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 */);
这篇关于用Java 8可选替换null检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!