I use object != null
a lot to avoid NullPointerException.
Is there a good alternative to this?
For example I often use:
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 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's Optional or FunctionalJava's Option. 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.