Objects.nonNull()
David M. Lloyd
david.lloyd at redhat.com
Thu Jan 13 23:58:36 UTC 2011
On 01/13/2011 05:36 PM, David Holmes wrote:
> 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.
It's plenty clear IMO if the method is declared as:
public static <T> T nonNull(T arg) throws NullPointerException
and is documented as such. Which it is, btw.
For another angle, compare to Class.cast(). It doesn't say that it
throws ClassCastException (i.e. throwIfWrongType), it just says what the
result is (the cast object). Granted it helps that "cast" is also a
verb. Maybe if 'notNull' is not clear enough, 'nullChecked' is more
appropriate; it talks about the result of the method rather that the
exceptional case.
T foo = clazz.cast(nullChecked(bar));
reads pretty well.
--
- DML
More information about the core-libs-dev
mailing list