I use object != null
a lot to avoid NullPointerException.
Is there a good alternative to this?
For example I often use:
Wow, I almost hate to add another answer when we have 57 different ways to recommend the NullObject pattern
, but I think that some people interested in this question may like to know that there is a proposal on the table for Java 7 to add "null-safe handling"—a streamlined syntax for if-not-equal-null logic.
The example given by Alex Miller looks like this:
public String getPostcode(Person person) {
return person?.getAddress()?.getPostcode();
}
The ?.
means only de-reference the left identifier if it is not null, otherwise evaluate the remainder of the expression as null
. Some people, like Java Posse member Dick Wall and the voters at Devoxx really love this proposal, but there is opposition too, on the grounds that it will actually encourage more use of null
as a sentinel value.
Update: An official proposal for a null-safe operator in Java 7 has been submitted under Project Coin. The syntax is a little different than the example above, but it's the same notion.
Update: The null-safe operator proposal didn't make it into Project Coin. So, you won't be seeing this syntax in Java 7.
Rather than Null Object Pattern -- which has its uses -- you might consider situations where the null object is a bug.
When the exception is thrown, examine the stack trace and work through the bug.
Depending on what kind of objects you are checking you may be able to use some of the classes in the apache commons such as: apache commons lang and apache commons collections
Example:
String foo;
...
if( StringUtils.isBlank( foo ) ) {
///do something
}
or (depending on what you need to check):
String foo;
...
if( StringUtils.isEmpty( foo ) ) {
///do something
}
The StringUtils class is only one of many; there are quite a few good classes in the commons that do null safe manipulation.
Here follows an example of how you can use null vallidation in JAVA when you include apache library(commons-lang-2.4.jar)
public DOCUMENT read(String xml, ValidationEventHandler validationEventHandler) {
Validate.notNull(validationEventHandler,"ValidationHandler not Injected");
return read(new StringReader(xml), true, validationEventHandler);
}
And if you are using Spring, Spring also has the same functionality in its package, see library(spring-2.4.6.jar)
Example on how to use this static classf from spring(org.springframework.util.Assert)
Assert.notNull(validationEventHandler,"ValidationHandler not Injected");
You have to check for object != null only if you want to handle the case where the object may be null...
There is a proposal to add new annotations in Java7 to help with null / notnull params: http://tech.puredanger.com/java7/#jsr308
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.
public static <T> T ifNull(T toCheck, T ifNull) {
if (toCheck == null) {
return ifNull;
}
return toCheck;
}