是不是风格使用NullPointerException测试null? [英] Is it bad style to use NullPointerException to test for null?

查看:183
本文介绍了是不是风格使用NullPointerException测试null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些符合以下模式的代码:

I have some code along the following pattern:

return a().b().c().d().e();

现在因为每个方法都可以返回 null ,通常会测试这个:

now since every one of those methods could return null, one would usually test for this:

if( (a()!=null) && (a().b() != null) && ....) {
   return a().b().c().d().e();
} else  {
  return null;
}

(可能使用一些局部变量来避免重复调用)

(and maybe use some local variables to avoid duplicate calls)

我很想尝试:

try {
   return a().b().c().d().e();
} catch (NullPointerException e) {
   return null;
}

这被认为是不好的风格吗?效率低?或者很确定?

Is that considered bad style? inefficient? Or quite ok?

推荐答案

不要这样做。与基本空检查相比,抛出和捕获异常相当昂贵。

Don't do this. Throwing and catching exceptions is fairly expensive when compared to basic null checks.

您可能也有兴趣知道已经为未来版本的Java提出了语法,这将使这更简单。它会像这样:

You might also be interested to know that syntax has been proposed for a future version of Java that would make this simpler. It would go something like this:

a()?.b()?.c()?.d()

?。操作将是。的可选版本。运算符。如果LHS为空,它将在该点返回null,而不是尝试评估RHS。正确的是你正在寻找什么,但我恐怕它没有为Java 7切割。不知道Java 8的此功能的状态。

The "?." operation would be an optional version of the "." operator. If LHS is null, it would return null at that point instead of trying to evaluate RHS. Exactly what you are looking for, but I am afraid it didn't make the cut for Java 7. Don't know the status of this feature for Java 8.

这篇关于是不是风格使用NullPointerException测试null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆