How to check multiple objects for nullity?

Krzysztof Wolny picture Krzysztof Wolny · Jul 23, 2015 · Viewed 39.5k times · Source

Often, I can see a code constructs like following:

if(a == null || b == null || c == null){
    //...
}

I wonder if there is any widely used library (Google, Apache, etc.) to check against nullity for multiple objects at once, e.g.:

if(anyIsNull(a, b, c)){
    //...
}

or

if(allAreNulls(a, b, c)){
    //...
}

UPDATE:

  1. I perfectly know how to write it by myself
  2. I know it can be the result of the poor program structure but it's not a case here
  3. Let's make it more challenging and replace original example with something like this:

    if(a != null && a.getFoo() != null && a.getFoo().getBar() != null){
        //...
    }
    

UPDATE 2:

I've created a pull request for Apache Commons Lang library to fix this gap:

These will be incorporated in commons-lang, version 3.5:

  • anyNotNull (Object... values)
  • allNotNull (Object... values)

Answer

tobias_k picture tobias_k · Jul 23, 2015

In Java 8, you could use Stream.allMatch to check whether all of the values match a certain condition, such as being null. Not much shorter, but maybe a bit easier to read.

if (Stream.of(a, b, c).allMatch(x -> x == null)) {
    ...
}

And analogeously for anyMatch and noneMatch.


About your "more challenging example": In this case, I think there is no way around writing a lazy-evaluated conjunction of null-checks, like the one you have:

if (a != null && a.getFoo() != null && a.getFoo().getBar() != null) {
    ...
}

Any of the other approaches, using streams, lists, or var-arg methods, would try to evaluate a.getFoo() before a has been tested not to be null. You could use Optional with map and method pointers, that will be lazily evaluated one after the other, but whether this makes it any more readable is debatable and may vary from case to case (particularly for longer class names):

if (Optional.ofNullable(a).map(A::getFoo).map(B::getBar).isPresent()) {
    ...
}

Bar bar = Optional.ofNullable(a).map(A::getFoo).map(B::getBar).orElse(null);

Another alternative might be to try to access the innermost item, but I have a feeling that this is not considered good practice, either:

try {
    Bar bar = a.getFoo().getBar();
    ...
catch (NullPointerException e) {
    ...
}

Particularly, this will also catch any other NPEs after accessing that element -- either that, or you have to put only the Bar bar = ... in the try and everything else in another if block after the try, nullifying any (questionable) gains in readability or brevity.


Some languages have a Safe Navigation Operator, but it seems like Java is not one of them. This way, you could use a notation like a?.getFoo()?.getBar() != null, where a?.getFoo() will just evaluate to null if a is null.