I have seen code where almost every variable in all application layers is checked for not being null. I have also seen code almost without this.
if(object != null){}
What are the best practices for checking if a variable is NULL? Where does it really make sense, and is getting a NullPointerException really a bad thing – is all this null checking maybe a symptom that your application is in poor health?
It is a good idea to check for null explicitly because:
If you get a
NullPointerExceptionyou might not be able to work out exactly which variable was null. Even if you have the line number where the exception was thrown, there might still be more than one variable on that line.It’s particularly important to put these checks in your public interface. This is because when your user provides an incorrect parameter they should get an
IllegalArgumentExceptiontelling them that they made an error. If they just get back aNullPointerExceptionthey can’t tell if they provided an incorrect parameter, or if there is just a bug in your code.