java 替换null,用Java 8可选替换null检查

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 */);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值