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.
I'm a fan of "fail fast" code. Ask yourself - are you doing something useful in the case where the parameter is null? If you don't have a clear answer for what your code should do in that case... I.e. it should never be null in the first place, then ignore it and allow a NullPointerException to be thrown. The calling code will make just as much sense of an NPE as it would an IllegalArgumentException, but it'll be easier for the developer to debug and understand what went wrong if an NPE is thrown rather than your code attempting to execute some other unexpected contingency logic - which ultimately results in the application failing anyway.
If you use (or planning to use) a Java IDE like JetBrains IntelliJ IDEA, Eclipse or Netbeans or a tool like findbugs then you can use annotations to solve this problem.
Basically, you've got
@Nullable
and@NotNull
.You can use in method and parameters, like this:
or
The second example won't compile (in IntelliJ IDEA).
When you use the first
helloWorld()
function in another piece of code:Now the IntelliJ IDEA compiler will tell you that the check is useless, since the
helloWorld()
function won't returnnull
, ever.Using parameter
if you write something like:
This won't compile.
Last example using
@Nullable
Doing this
And you can be sure that this won't happen. :)
It's a nice way to let the compiler check something more than it usually does and to enforce your contracts to be stronger. Unfortunately, it's not supported by all the compilers.
In IntelliJ IDEA 10.5 and on, they added support for any other
@Nullable
@NotNull
implementations.See blog post More flexible and configurable @Nullable/@NotNull annotations.
Doing this in your own code and you can avoid != null checks.
Most of the time null checks seem to guard loops over collections or arrays, so just initialise them empty, you won't need any null checks.
There is a tiny overhead in this, but it's worth it for cleaner code and less NullPointerExceptions.
Java 7 has a new
java.util.Objects
utility class on which there is arequireNonNull()
method. All this does is throw aNullPointerException
if its argument is null, but it cleans up the code a bit. Example:The method is most useful for checking just before an assignment in a constructor, where each use of it can save three lines of code:
becomes
Ultimately, the only way to completely solve this problem is by using a different programming language:
nil
, and absolutely nothing will happen. This makes most null checks unnecessary, but it can make errors much harder to diagnose.If undefined values are not permitted:
You might configure your IDE to warn you about potential null dereferencing. E.g. in Eclipse, see Preferences > Java > Compiler > Errors/Warnings/Null analysis.
If undefined values are permitted:
If you want to define a new API where undefined values make sense, use the Option Pattern (may be familiar from functional languages). It has the following advantages:
Java 8 has a built-in
Optional
class (recommended); for earlier versions, there are library alternatives, for example Guava'sOptional
or FunctionalJava'sOption
. But like many functional-style patterns, using Option in Java (even 8) results in quite some boilerplate, which you can reduce using a less verbose JVM language, e.g. Scala or Xtend.If you have to deal with an API which might return nulls, you can't do much in Java. Xtend and Groovy have the Elvis operator
?:
and the null-safe dereference operator?.
, but note that this returns null in case of a null reference, so it just "defers" the proper handling of null.