简体   繁体   English

空安全布尔表达式评估

[英]Null safe boolean expression evaluation

Is there a Null and NullPointer safe way to evaluate boolean expressions. 是否有Null和NullPointer安全的方法来评估布尔表达式。

Here's an example from our codebase - 这是我们代码库中的一个示例-

private boolean serviceReturnedSuccess(Response response) {
    boolean isSuccess = true;
    if (response.hasMetadata()) {
        Metadata responseMetadata = response.getMetadata();
        if (responseMetadata.hasReturnCode()) {
            if (responseMetadata.getReturnCode() != 0) {
                isSuccess = false;
            }
        }
    }
    return isSuccess;
}

What I would like to write is - 我想写的是-

private boolean serviceReturnedSuccess(Response response) {
    return NullSafeBooleanEvaluator.valueOf(response.getMetadata().getReturnCode() != 0);
}

I couldn't find something that does this out of the box when I looked at BooleanUtils in apache commons or in Guava's common object utils . 当我查看apache commonsGuava's common object utils中的 BooleanUtils时,找不到开箱即用的东西。

I am ideally looking for an implementation in one of the standard libraries, otherwise I'm looking for a generic way to implement this. 理想情况下,我正在一个标准库中寻找实现,否则,我正在寻找一种通用的实现方法。

There can't be a NullSafeBooleanEvaluator.valueOf(response.getMetadata().getReturnCode() != 0) since the argument expression must be evaluated before it is passed to NullSafeBooleanEvaluator.valueOf() . 不能有NullSafeBooleanEvaluator.valueOf(response.getMetadata().getReturnCode() != 0)因为必须在将参数表达式传递给NullSafeBooleanEvaluator.valueOf()之前对其求值。 The closest solution would be 最接近的解决方案是

private boolean serviceReturnedSuccess(Response response) {
    try {
        return response.getMetadata().getReturnCode() != 0;
    }
    catch (NullPointerException e) {
        return false;
    }
}

which of course has some code smell. 哪个当然有一些代码味道。

As Egor already commented Java 8 introduced the new Optional class for such problems (see also this informative article ): 正如Egor所评论的那样,Java 8针对此类问题引入了新的Optional类(另请参见此参考文章 ):

But I am not convinced that it leads to readable code: 但是我不相信它会导致可读代码:

if (response.flatMap(Response::getMetadata).map(MetaData::getReturnCode).orElse(0) != 0)

(probably lot of errors in this code, but you get the idea). (此代码中可能有很多错误,但您知道了)。

The above article also mentions Groovy's safe navigation operator ? 上面的文章还提到了Groovy的安全导航运算符 which allows for a very elegant expression: 这使得表达非常优雅:

 if (response.getMetaData()?.getResponseCode()? != 0)

(again not tested). (再次未经测试)。 But Java is not Groovy, so I think your current code is probably the optimum if you don't want/can't use Optionals. 但是Java不是Groovy,因此,如果您不希望/不能使用Optionals,我认为您当前的代码可能是最佳的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM