对于以下代码,声纳向我抛出了严重违规 - 正确性 - 先前取消引用的状态值的空检查
有人可以就我在这里做错什么提出建议吗?
public boolean isExactMacthBill(AddressResponse response) {
boolean exactMatch = false;
if (null != response && null != response.getHostResponse()) {
HostResponseDetail hostResponse = response.getHostResponse();
String addressStatus = hostResponse.getMatchStatus();
ResponseDetail status = hostResponse.getStatus();
String addressMatchCode = status.getCode();
if (null != response.getMatchedAddresses() && response.getMatchedAddresses().size() > 0 && status != null) {
if (addressStatus.equalsIgnoreCase(Constants.USPS_MATCH)
|| (addressStatus.equalsIgnoreCase(Constants.PARTIAL_MATCH)
&& addressMatchCode.equalsIgnoreCase("3SXU"))) {
exactMatch = true;
} else
exactMatch = false;
}
}
return exactMatch;
}
Run Code Online (Sandbox Code Playgroud)
实际问题出在突出显示的问题之后——你有:
if (... && status != null)
Run Code Online (Sandbox Code Playgroud)
只需删除该检查,我认为 SonarLint 会很高兴。这是不必要的,因为如果status为 null 那么status.getCode()在达到该条件之前已经抛出异常。
从根本上说,您需要知道是否getStatus() 应该返回 null - 您是否必须明确处理这种情况。如果这样做,您应该在调用之前检查它status.getCode(),并做出相应的反应。如果您不这样做,则可以调用该getCode()方法 - 如果您的假设不正确,您将得到一个NullPointerException正常的结果,这可能是“世界并不像我期望的那样”场景的最合适的结果”。但是,在您已经依赖它为非空之后,您不应该尝试“处理”它为空。