[英]Null safe boolean expression evaluation
是否有Null和NullPointer安全的方法來評估布爾表達式。
這是我們代碼庫中的一個示例-
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;
}
我想寫的是-
private boolean serviceReturnedSuccess(Response response) {
return NullSafeBooleanEvaluator.valueOf(response.getMetadata().getReturnCode() != 0);
}
當我查看apache commons
或Guava's
common object utils中的 BooleanUtils
時,找不到開箱即用的東西。
理想情況下,我正在一個標准庫中尋找實現,否則,我正在尋找一種通用的實現方法。
不能有NullSafeBooleanEvaluator.valueOf(response.getMetadata().getReturnCode() != 0)
因為必須在將參數表達式傳遞給NullSafeBooleanEvaluator.valueOf()
之前對其求值。 最接近的解決方案是
private boolean serviceReturnedSuccess(Response response) {
try {
return response.getMetadata().getReturnCode() != 0;
}
catch (NullPointerException e) {
return false;
}
}
哪個當然有一些代碼味道。
正如Egor所評論的那樣,Java 8針對此類問題引入了新的Optional類(另請參見此參考文章 ):
但是我不相信它會導致可讀代碼:
if (response.flatMap(Response::getMetadata).map(MetaData::getReturnCode).orElse(0) != 0)
(此代碼中可能有很多錯誤,但您知道了)。
上面的文章還提到了Groovy的安全導航運算符 ? 這使得表達非常優雅:
if (response.getMetaData()?.getResponseCode()? != 0)
(再次未經測試)。 但是Java不是Groovy,因此,如果您不希望/不能使用Optionals,我認為您當前的代碼可能是最佳的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.