There is A LOT of information online stating that you should NEVER catch a NullPointerException. Generally I agree, but I am wondering about this one case.
I have inherited code that requires me to access data that I need in the following way
context.getGrandParent().getParent().getChild().isRequired()
There is no guarantee that any of the objects in this hierarchy will not be null. I have to enter a block if isRequired() returns true. First, and what I initially wrote, with null checks:
if(context != null && context.getGrandParent() != null && context.getGrandParent().getParent() != null && context.getGrandParent().getParent().getChild() != null && context.getGrandParent().getParent().getChild().isRequired() ){ // continue with business logic } else { LOG.error("Unable to determine if processing is required."); } // continue with other inherited code
Setting aside that I could refactor this, perhaps for readability, wouldn’t it make more sense to do the following?
boolean isRequired = false; try { isRequired = context.getGrandParent().getParent().getChild().isRequired(); } catch (NullPointerException npe) { LOG.error("Unable to determine if processing is required."); } if(isRequired){ // continue with business logic } // continue with other inherited code