java通过使用try-catch避免了无休止的空/空检查
假设我想访问
productList.get(0).getCustomerList().get(0).getAddressList().get(0).getRegion.getCode()
在每个级别,我都需要检查空列表或空列表。数据结构非常复杂,重构可能是一种选择,但也可能太复杂或不可能
由此产生的代码将是:
if(productList != null
&& !productList.isEmpty()
&& productList.get(0).getCustomerList().get(0) != null
&& ...){
return productList.get(0).getCustomerList().get(0).getAddressList(0).getRegion.getCode();
}
由此产生的代码丑陋、冗长,没有任何真正的业务逻辑,而且很难阅读。有什么聪明的方法可以避免这种情况吗?是否可以接受这样做:
try{
return productList.get(0).getCustomerList().get(0).getAddressList(0).getRegion.getCode();
} catch(NullPointerException | IndexOutOfBoundException e){
return null;
}
# 1 楼答案
下面是使用Java8可选的另一个建议