I use object != null
a lot to avoid NullPointerException
.
Is there a good alternative to this?
For example:
if (someobject != null) {
someobject.doCalc();
}
This avoids a NullPointerException
, when it is unknown if the object is null
or not.
Note that the accepted answer may be out of date, see https://stackoverflow.com/a/2386013/12943 for a more recent approach.
If null-values are not allowed
If your method is called externally, start with something like this:
Then, in the rest of that method, you'll know that
object
is not null.If it is an internal method (not part of an API), just document that it cannot be null, and that's it.
Example:
However, if your method just passes the value on, and the next method passes it on etc. it could get problematic. In that case you may want to check the argument as above.
If null is allowed
This really depends. If find that I often do something like this:
So I branch, and do two completely different things. There is no ugly code snippet, because I really need to do two different things depending on the data. For example, should I work on the input, or should I calculate a good default value?
It's actually rare for me to use the idiom "
if (object != null && ...
".It may be easier to give you examples, if you show examples of where you typically use the idiom.
Sometimes, you have methods that operate on its parameters that define a symmetric operation:
If you know b can never be null, you can just swap it. It is most useful for equals: Instead of
foo.equals("bar");
better do"bar".equals(foo);
.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:
Note that addParam() returns self, so that you can add more parameters to check.
Method
validate()
will throw checkedValidationException
if any of the parameters is null (checked or unchecked is more a design/taste issue, but myValidationException
is checked).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.
This is a very common problem for every Java developer. So there is official support in Java 8 to address these issues without cluttered code.
Java 8 has introduced
java.util.Optional<T>
. It is a container that may or may not hold a non-null value. Java 8 has given a safer way to handle an object whose value may be null in some of the cases. It is inspired from the ideas of Haskell and Scala.In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional<T> class forces you to think about the case when the value is not present. As a consequence, you can prevent unintended null pointer exceptions.
In above example we have a home service factory that returns a handle to multiple appliances available in the home. But these services may or may not be available/functional; it means it may result in a NullPointerException. Instead of adding a null
if
condition before using any service, let's wrap it in to Optional<Service>.WRAPPING TO OPTION<T>
Let's consider a method to get a reference of a service from a factory. Instead of returning the service reference, wrap it with Optional. It lets the API user know that the returned service may or may not available/functional, use defensively
As you see
Optional.ofNullable()
provides an easy way to get the reference wrapped. There are another ways to get the reference of Optional, eitherOptional.empty()
&Optional.of()
. One for returning an empty object instead of retuning null and the other to wrap a non-nullable object, respectively.SO HOW EXACTLY IT HELPS TO AVOID A NULL CHECK?
Once you have wrapped a reference object, Optional provides many useful methods to invoke methods on a wrapped reference without NPE.
Optional.ifPresent invokes the given Consumer with a reference if it is a non-null value. Otherwise, it does nothing.
Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects. It is so clean and easy to understand. In the above code example,
HomeService.switchOn(Service)
gets invoked if the Optional holding reference is non-null.We use the ternary operator very often for checking null condition and return an alternative value or default value. Optional provides another way to handle the same condition without checking null. Optional.orElse(defaultObj) returns defaultObj if the Optional has a null value. Let's use this in our sample code:
Now HomeServices.get() does same thing, but in a better way. It checks whether the service is already initialized of not. If it is then return the same or create a new New service. Optional<T>.orElse(T) helps to return a default value.
Finally, here is our NPE as well as null check-free code:
The complete post is NPE as well as Null check-free code … Really?.
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:
The
?.
means only de-reference the left identifier if it is not null, otherwise evaluate the remainder of the expression asnull
. 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 ofnull
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.
May I answer it more generally!
We usually face this issue when the methods get the parameters in the way we not expected (bad method call is programmer's fault). For example: you expect to get an object, instead you get a null. You expect to get an String with at least one character, instead you get an empty String ...
So there is no difference between:
}
or
They both want to make sure that we received valid parameters, before we do any other functions.
As mentioned in some other answers, to avoid above problems you can follow the Design by contract pattern. Please see http://en.wikipedia.org/wiki/Design_by_contract.
To implement this pattern in java, you can use core java annotations like javax.annotation.NotNull or use more sophisticated libraries like Hibernate Validator.
Just a sample:
Now you can safely develop the core function of your method without needing to check input parameters, they guard your methods from unexpected parameters.
You can go a step further and make sure that only valid pojos could be created in your application. (sample from hibernate validator site)