I use object != null
a lot to avoid NullPointerException.
Is there a good alternative to this?
For example I often use:
The Google collections framework offers a good and elegant way to achieve the null check.
There is a method in a library class like this:
static T checkNotNull(T e) {
if (e == null) {
throw new NullPointerException();
}
return e;
}
And the usage is (with import static
):
...
void foo(int a, Person p) {
if (checkNotNull(p).getAge() > a) {
...
}
else {
...
}
}
...
Or in your example:
checkNotNull(someobject).doCalc();