Objects.nonNull()
Brian Goetz
brian.goetz at oracle.com
Thu Jan 13 22:38:59 UTC 2011
>> and
>> public static<T> T nonNull(String obj) {
>> return (obj == null) ? "" : obj;
>> }
>> etc.
>
> I don't know, this doesn't feel right to me. It would probably make more
> sense to have a:
>
> public static <T> T defaulted(T test, T defVal) {
> return test == null ? defVal : test;
> }
>
> This would cover both of the above cases and more.
Right, my exposition suffered from my desire to keep it short and not
get ratholed on the details of the carpet-sweeping methods (which was
unsuccessful.) The above is (clearly) the general case, but in the code
bases I've seen this in, its nearly always paired with specific versions
for String (default "") and arrays (default empty array.)
People use these to simplify cases like
if (foo != null)
for (Foo f : foo) { ... }
to
for (Foo f : nonNull(foo)) { ... }
It is an extremely common pattern; I've seen it in nearly every
nontrivial code base I've worked with. Frequently multiple times in the
same code base :(
Summarizing, the fail-fast and the carpet-sweeping behavior are both
valid and common use cases. The current naming is not only confusing
but basically forecloses on ever offering the carpet-sweeping behavior,
which, despite objections from some, is something people do all the time.
More information about the core-libs-dev
mailing list