Objects.nonNull()

Brian Goetz brian.goetz at oracle.com
Fri Jan 14 00:06:24 UTC 2011


For clarification only (we're not suggesting adding these NOW, but 
instead preserving the option):

People constantly write methods like

   public String nonNull(String s) { return s != null ? s : "" }

and other versions (including the more general version that takes a 
default, and versions for arrays) because they are getting values from 
possibly null-dispensing sources (such as maps or other key-value 
stores).  They find locutions like

   (s != null && s.length() > 0)

to be excessively verbose in these cases.  So they write utility methods 
that translate null to some benign default (empty string, empty array), 
and proceed on their way.  People do this all the time; what they want 
is for the null check to recede into the background so the program logic 
is more apparent.

People hate the fact that if the array/collection is null, foreach 
throws NPE; they'd mostly rather not have to deal explicitly with the 
null case.  Providing a something that reads more smoothly (like 
checkNonNull(x)) will make them happier.





On 1/13/2011 6:57 PM, Ulf Zibis wrote:
> Am 13.01.2011 23:38, schrieb Brian Goetz:
>>
>> People use these to simplify cases like
>>
>> if (foo != null)
>> for (Foo f : foo) { ... }
>>
>> to
>>
>> for (Foo f : nonNull(foo)) { ... }
>
> To be honest, I don't understand the real value of nonNull().
> If the argument is null, NPE would be thrown anyway.
> Do I miss something?
>
> -Ulf
>



More information about the core-libs-dev mailing list