Bear with me, as I've read a bit on this and I'm still not sure if I'm thinking about this correctly, but I want to understand this fully...
I've recently found myself in a debate that surrounds a pragmatic approach to code, whereby the feedback I've been given is (I think) a misrepresentation of general Software Engineering advice.
So consider you have a method that handles an input - let's say you take in a String and format in a particular way (assume it's not a way that any existing Java until provides). The method could throw a NPE if null is passed in, because that shouldn't happen.
I didn't add in any NPE handling like the Apache Commons library for StringUtils has, where when you pass in null
it provides back an empty string because, in the context of the method, a null
shouldn't be provided. I wanted to leave it up to the implementation to determine how to handle this.
The logic for this, by me, is that you wouldn't necessarily want this null
value to just be swallowed as normal, but might want to catch this and rethrow the occurance as another exception to explain "this shouldn't have happened" - say, if it was for a step that was considered mandatory.
A colleagues said that "catching NPEs is considered bad practice", but further research on this suggests this is only the case where you're ignoring the NPE (or swallowing it).
To my mind, that's what
if(var = null) { return ""; }
(for example) is doing, whilst actually handling the null as an exception...
try {
myStringMethod( somevar );
}
catch ( final NullPointerException e )
{
Throw new MySpecificException( e );
}
... Is an effective way of handling a mandatory value that shouldn't be null.
In the way it was put across, it seems to suggest a NPE should never be seen - which I agree with, but surely "dealing with it" by somewhat ignoring the cause is actually the wrong way?