Proposal: Elvis and Other Null-Safe Operators

Joseph D. Darcy Joe.Darcy at Sun.COM
Mon Jul 6 09:42:45 PDT 2009


If the existing gamut of null-safe operators are added, they could be 
used before the for-each loop to guard against null; the for-loop itself 
does not need to change.

-Joe

Winson Quock wrote:
> Hi,
>
> I would like to add one small addition to this proposal, if it is not too
> late.
>
> Null-safe for-each loop:
>
> List<String> strings = null; // could be null
> for (String s : string) { // if list or array is null, do not throw NPE but
> skip the loop
>  ...
> }
>
> ADVANTAGE:
>
> 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
>     ...
>   }
> }
>
> COMPATIBILITY: This is generally backward compatibility except perhaps some
> very arcane codes depending on the throwing of NPE to function correctly,
> like
>
> int totalLen = 0;
> try {
>   for (String s : string) { // if list or array is null, do not throw NPE
> but skip the loop
>     totalLen += s.length();
>   }
> } catch (NullPointerException e) {
>   totalLength = -1;
> }
>
> Such practices should be exceeding rare and should not be a concern, or we
> can introduce a -X compiler option to restore the original behavior.
>
> ALTERNATIVE: Use a new '?:' operator for null-safe loop, similar to those
> other operators proposed by this proposal
>
> for (String s ?: string) { // if list or array is null, do not throw NPE but
> skip the loop
>  ...
> }
>
> This alleviates the compatibility issue with the arcane case above.
>
>   




More information about the coin-dev mailing list