I use object != null
a lot to avoid NullPointerException.
Is there a good alternative to this?
For example I often use:
Common "problem" in Java indeed.
First, my thoughts on this:
I consider that it is bad to "eat" something when NULL was passed where NULL isn't a valid value. If you're not exiting the method with some sort of error then it means nothing went wrong in your method which is not true. Then you probably return null in this case, and in the receiving method you again check for null, and it never ends, and you end up with "if != null", etc..
So, IMHO, null must be a critical error which prevents further execution (that is, where null is not a valid value).
The way I solve this problem is this:
First, I follow this convention:
And finally, in the code, the first line of the public method goes like this:
ValidationUtils.getNullValidator().addParam(plans, "plans").addParam(persons, "persons").validate();
Note that addParam() returns self, so that you can add more parameters to check.
Method validate()
will throw checked ValidationException
if any of the parameters is null (checked or unchecked is more a design/taste issue, but my ValidationException
is checked).
void validate() throws ValidationException;
The message will contain the following text if, for example, "plans" is null:
"Illegal argument value null is encountered for parameter [plans]"
As you can see, the second value in the addParam() method (string) is needed for the user message, because you cannot easily detect passed-in variable name, even with reflection (not subject of this post anyway...).
And yes, we know that beyond this line we will no longer encounter a null value so we just safely invoke methods on those objects.
This way, the code is clean, easy maintainable and readable.