Objects.nonNull()

David Holmes David.Holmes at oracle.com
Thu Jan 13 23:36:42 UTC 2011


Brian Goetz said the following on 01/14/11 09:15:
>>> to go either way (both checkNonNull and ensureNonNull better
>>> match the actual behavior of the method than plain nonNull) but
>>> we might as well pick the right convention.
>>
>> Rémi's throwIfNull(x) suggestion does capture the precise meaning,
>> though it begs the question of what, exactly, will be thrown.
> 
> In either case the Javadoc specifies a @throws clause that will guide 
> readers to the answer on this.
> 
> Between checkNonNull() and throwIfNull(), I lean towards the former.  In 
> any case the answer should be driven by what is more obvious to the 
> reader.  So let's look at some typical code:
> 
>   public Moo fooWrapper(String x, String y) {
>       return foo(throwIfNull(x), throwIfNull(y));
>   }
> 
> vs
> 
>   public Moo fooWrapper(String x, String y) {
>       return foo(checkNonNull(x), checkNonNull(y));
>   }
> 
> Since throwing should be the exceptional path, it feels to me that 
> having throw in the name sets slightly the wrong expectations.  (It's 
> sort of like the old MASH episode where one of them is defusing a bomb 
> while the other reads the instructions over the phone: "cut the red 
> wire" (snip) "but first..." (panic ensues).)  Its the difference between 
> "proceed if ok" and "blow up if not ok"; both mean the same thing but if 
> OK is the common case, the former seems the more appropriate phrasing.

But the argument was that nonNull (which Josh added by the way) and 
checkNonNull, don't make it clear as to what happens if it is indeed 
null. Whether the expected case or not, throwIfNull makes it very clear.

I must confess that my +1 for throwIfNull was made before I realized 
that this method returns the reference - in which case throwIfNull 
doesn't tell you anything about what happens if it isn't null (the same 
argument against the original naming).

David



More information about the core-libs-dev mailing list