I use object != null
a lot to avoid NullPointerException.
Is there a good alternative to this?
For example I often use:
Java 7 has a new java.util.Objects
utility class on which there is a requireNonNull()
method. All this does is throw a NullPointerException
if its argument is null, but it cleans up the code a bit. Example:
Objects.requireNonNull(someObject);
someObject.doCalc();
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:
Parent(Child child) {
if (child == null) {
throw new NullPointerException("child");
}
this.child = child;
}
becomes
Parent(Child child) {
this.child = Objects.requireNonNull(child, "child");
}