如何避免在方法链中检查空值? [英] How to avoid checking for null values in method chaining?

查看:116
本文介绍了如何避免在方法链中检查空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查某个值是否为null。如果它不为null,那么只需将一些变量设置为true即可。这里没有其他声明。我得到了太多像这样的条件检查。

I need to check if some value is null or not. And if its not null then just set some variable to true. There is no else statement here. I got too many condition checks like this.

有没有办法处理这个空检查而不检查所有方法返回值?

Is there any way to handle this null checks without checking all method return values?

if(country != null && country.getCity() != null && country.getCity().getSchool() != null && country.getCity().getSchool().getStudent() != null .....) {
    isValid = true;
}

我想直接检查变量并忽略NullpointerException。这是一个好习惯吗?

I thought directly checking variable and ignore NullpointerException. Is this a good practice?

try{
    if(country.getCity().getSchool().getStudent().getInfo().... != null)
} catch(NullPointerException ex){
    //dont do anything.
}


推荐答案

不,一般不会在Java中捕获NPE而不是对引用进行空值检查的良好实践。

No, it is generally not good practice in Java to catch a NPE instead of null-checking your references.

您可以使用 可选 如果您愿意,可以选择 : / p>

You can use Optional for this kind of thing if you prefer:

if (Optional.ofNullable(country)
            .map(Country::getCity)
            .map(City::getSchool)
            .map(School::getStudent)
            .isPresent()) {
    isValid = true;
}

或只是

boolean isValid = Optional.ofNullable(country)
                          .map(Country::getCity)
                          .map(City::getSchool)
                          .map(School::getStudent)
                          .isPresent();

如果那就是 isValid 应该是要检查。

if that is all that isValid is supposed to be checking.

这篇关于如何避免在方法链中检查空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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