Proposal: Elvis and Other Null-Safe Operators

Tom Hawtin Thomas.Hawtin at Sun.COM
Mon Jul 6 09:51:15 PDT 2009


Winson Quock wrote:

> This replace the current cumbersome and often forgot checks
> 
> if (string != null) {
>   for (String s : string) { // if list or array is null, do not throw NPE
> but skip the loop
>     ...
>   }
> }

Note, you can do this in a more source-friendly way with a little helper 
method:

    for (String s : maybe(string)) {
        ...
    }

where wrapNull is something along the lines of:

    public static <E> Iterable<E> maybe(Iterable<E> iterable) {
         return iterable==null ? Collections.<E>emptyList() : iterable;
    }

For arrays (can we get away for reference arrays, plz?)

    public static <E> Iterable<E> maybe(E[] array) {
         return array==null ?
             Collections.<E>emptyList() :
             Arrays.<E>asList(array);
    }


I believe @Nonnull will help with forgetful programmers. Usual advice 
applies to avoid nulls, particularly as substitutes for empty collections.

Tom Hawtin



More information about the coin-dev mailing list