Suppose I want to access something like
productList.get(0).getCustomerList().get(0).getAddressList().get(0).getRegion.getCode()
And at each level I need to check for null or empty list. The data structure is really complicated, and refactoring could be an option, but could as well be too complicated or impossible.
The resulting code would be:
if(productList != null
&& !productList.isEmpty()
&& productList.get(0).getCustomerList().get(0) != null
&& ...){
return productList.get(0).getCustomerList().get(0).getAddressList(0).getRegion.getCode();
}
The resulting code is ugly, verbose, doesn't carry any real business logic and is hard to read. Is there some smart way to avoid that? Would it be acceptable to do:
try{
return productList.get(0).getCustomerList().get(0).getAddressList(0).getRegion.getCode();
} catch(NullPointerException | IndexOutOfBoundException e){
return null;
}