85

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)
tobias_k
  • 81,265
  • 12
  • 120
  • 179
Krzysztof Wolny
  • 10,576
  • 4
  • 34
  • 46
  • 5
    It's easy to write but I rarely encountered such a need. Did you consider the possibility that your data might be poorly structured ? – Denys Séguret Jul 23 '15 at 08:53
  • 1
    if you want this kind of direct null check, you can simply create utility by passing it in list and iterate on it. – Panther Jul 23 '15 at 08:55
  • 2
    @Panther A list ? A variadic function seems more relevant here. – Denys Séguret Jul 23 '15 at 08:55
  • @DenysSéguret yes that will be better – Panther Jul 23 '15 at 08:58
  • 3
    One problem I could see from this kind of code is that the exception you would be throwing could not actually tell you the name of the parameter that is null when it shouldn't be. – Sebastiaan van den Broek Jul 23 '15 at 09:00
  • About your "more challenging example" and steams: This won't work, either. You are right that the stream itself is evaluated lazily, but the elements you put _into_ the stream are evaluated immediately. See my updated answer. – tobias_k Jul 24 '15 at 08:25
  • There are also [some](http://stackoverflow.com/q/14442299/1639625) [similar](http://stackoverflow.com/q/9066765/1639625) [questions](http://stackoverflow.com/q/10391406/1639625) on the same problem. – tobias_k Jul 24 '15 at 08:29

8 Answers8

64

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. You could emulate behavior like this with a custom function and a lambda, though, returning an Optional or just a value or null if you prefer:

public static <T> Optional<T> tryGet(Supplier<T> f) {
    try {
        return Optional.of(f.get());
    } catch (NullPointerException e) {
        return Optional.empty();
    }
}

Optional<Bar> bar = tryGet(() -> a.getFoo().getBar(););
tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • 12
    Oh, that's actually a nice idea. Additionally, [`Objects::isNull`](http://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#isNull-java.lang.Object-) could be used as a predicate. – Petr Janeček Jul 23 '15 at 09:05
  • 1
    Nice, thanks for this solution. However I would replace `x -> x == null` with `Objects::isNull`. It's a bite nicer imo. – Pieter De Bie Oct 25 '17 at 06:33
  • And a version to check if any is null. `if (Stream.of(a, b, b).anyMatch(Objects::isNull))` – Justin Mar 09 '18 at 08:33
  • I have found that the need of digging for a value through an objects internal structure to be somewhat of a code smell. To avoid such digging, try to instead have the client to provide the values needed in a more raw format. Compare: `public void smell(A a) { if(a != null && a.getFoo() != null && a.getFoo().getBar() != null) ... }` vs `public void clean(Bar bar) { if(bar != null) ... }` – Nadrendion Jan 07 '20 at 12:44
61

EDIT 2018: As of Apache Commons lang 3.5, there has been ObjectUtils.allNotNull() and ObjectUtils.anyNotNull().


No.

None of Apache Commons Lang (3.4), Google Guava (18) and Spring (4.1.7) provide such a utility method.

You'll need to write it on your own if you really, really need it. In modern Java code, I'd probably consider need for such a construct a code smell, though.

Petr Janeček
  • 37,768
  • 12
  • 121
  • 145
  • 1
    That's a bit weird for me, as there are classes like `Objects` when they check e.g. for first not null object. But non of them checks for all or non null objects. – Krzysztof Wolny Jul 24 '15 at 06:53
  • @KrzysztofWolny Yeah, they are all designed for working with a single possibly-null parameter. I haven't ever seen a method dealing with multiple of them, nor do I think I ever needed it. That would be part of why I think the common libraries don't include them - the demand might be there, but it's probably not very high. But of course, every programmer works differently, so such a method might be exactly what you need. Feel free to file a feature request for your favorite library! – Petr Janeček Jul 24 '15 at 07:05
  • 2
    @Slantec will consider that, now with GitHub and its pull requests it's so easy :) And Apache has mirrors in GH as well. – Krzysztof Wolny Jul 24 '15 at 07:11
  • 1
    Actually, there is already a ticket for it in Apache Commons Lang project :) https://issues.apache.org/jira/browse/LANG-781 – Krzysztof Wolny Jul 24 '15 at 07:22
  • @KrzysztofWolny Aha, and it also points out that the [`Validate`](http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/Validate.html) class contains almost exactly what you need. Not quite, but almost! :) – Petr Janeček Jul 24 '15 at 08:43
  • I know this is an old post, but I see that you've updated your post to include the newest addition of the null check method (cheers for that), so I wanted to see if you still think it's a code smell because I don't see it as such. Null check is a fact of life for Java programmers, and my opinion is that having a clear method name that does that is a clean code. There are many ways to avoid null, but null checks are not always avoidable despite of your best intention. – THIS USER NEEDS HELP Mar 22 '18 at 18:29
  • 1
    @THISUSERNEEDSHELP I still do. It may be just my coding style, but I like to get rid of nulls in the system as soon as possible by `Preconditions.checkNotNull(something, "something")`. When checking for multiple nulls, I usually need to know which one of them was null, and that cannot be achieved by a single method. This does _not_ mean that my methods never return null, they sometimes do. But in general this is limited as other constructs are preferred by me. I do not think I had a use for such a method in many years, with the exception of array of objects. – Petr Janeček Mar 26 '18 at 23:50
13

You could also use something like the following method. It allows you to pass as many parameters as you want:

public static boolean isAnyObjectNull(Object... objects) {
    for (Object o: objects) {
        if (o == null) {
            return true;
        }
    }
    return false;
}

You call it with as many parameters as you like:

isAnyObjectNull(a, b, c, d, e, f);

You could do something similar for areAllNull.

public static boolean areAllObjectsNull(Object... objects) {
    for (Object o: objects) {
        if (o != null) {
            return false;
        }
    }
    return true;
}

Note: you could also use the ternary operator instead of if (o == null). The two methods shown here have no error handling. Adjust it to your needs.

kamwo
  • 1,980
  • 1
  • 23
  • 32
  • 2
    For `areAllNull`, just return `false` if `o != null`? – tobias_k Jul 23 '15 at 09:36
  • @tobias_k: You are absolute correct. I deleted my comment and edited the code. – kamwo Jul 23 '15 at 09:47
  • why do you use Boolean instead of the primitive boolean ? – AlexWien Aug 04 '15 at 20:20
  • @AlexWien: You can use whatever you like (primitive or object). Change the methods to your needs. Sometimes you have to work with a lot of Boolean objects in an application. By using the `Boolean.FALSE` / `Boolean.TRUE` I receive _static_ objects. This way there exist only two in the whole system and the system does not have to create new objects. Each time I call this method or another it will return me the references to the existing ones. – kamwo Aug 04 '15 at 21:33
  • 1
    @kamwo when you are using primitives the system also does not have to create new objects – Laurens Op 't Zandt Sep 22 '17 at 14:55
  • @LaurensOp'tZandt I'm absolutely aware of this :-) – kamwo Sep 23 '17 at 09:34
5

Objects.requireNonNull

It is possible with help of Objects class and its requireNonNull method.

public static void requireNonNull(Object... objects) {
    for (Object object : objects) {
        Objects.requireNonNull(object);
    }
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
viavad
  • 373
  • 7
  • 17
  • 2
    `requireNonNull` throws exception. It is better suited for enforcing contracts, rather than testing for nullability, when null is not an exceptional scenario. – schatten Nov 09 '20 at 19:30
3

Apache commons-lang3 since version 3.11 has method ObjectUtils.allNull(Object... values)

ObjectUtils.allNull(obj1, obj2, obj3);
Vadim Zverev
  • 468
  • 6
  • 14
1

Simply as that:

Stream.of(a,b,c).allMatch(Objects::nonNull)
Domenico
  • 1,331
  • 18
  • 22
0

I was looking for a solution, but I don't have apache as a dependency yet and it felt silly to me to add it just for the allNonNull method. Here is my plain vanilla java solution using Predicate#and() / Predicate#or() like this:

private static boolean allNonNull(A a) {
    Predicate<A> isNotNull = Objects::nonNull; 
    Predicate<A> hasFoo = someA -> someA.foo != null;
    Predicate<A> hasBar = someA -> someA.foo.bar != null;
    return Optional.ofNullable(a)
        .filter(isNotNull.and(hasFoo.and(hasBar)))
        .isPresent();
}

Note: for the anyNonNull, simply use the or() method instead of and().

When invoked, would give the following output:

    System.out.println(isValid(new A(new Foo(new Bar())))); // true
    System.out.println(isValid(new A(new Foo(null)))); // false
    System.out.println(isValid(new A(null))); // false
    System.out.println(isValid(null)); // false

Class definitions used:

public static class A {
    public A(Foo foo) {
        this.foo = foo;
    }
    Foo foo;
}

public static class Foo {
    public Foo(Bar bar) {
        this.bar = bar;
    }
    Bar bar;
}

public static class Bar { }
BitfulByte
  • 4,117
  • 1
  • 30
  • 40
-2

You can create a list of you objects and use yourList.contains(null) in it.

List < Object > obList = new ArrayList < Object > ();

String a = null;
Integer b = 2;
Character c = '9';

obList.add(a);
obList.add(b);
obList.add(c);

System.out.println("List is " + obList);

if (obList.contains(null)) {
    System.out.println("contains null");
} else {
    System.out.println("does not contains null");
}

DEMO

singhakash
  • 7,891
  • 6
  • 31
  • 65
  • 2
    Nice. Or, to make it actually shorter than the original, use `Arrays.asList(a, b, c).contains(null)`. Won't work for all-null, though... – tobias_k Jul 23 '15 at 09:31