Objects.nonNull()
David Schlosnagle
schlosna at gmail.com
Fri Jan 14 00:39:27 UTC 2011
On Thu, Jan 13, 2011 at 7:06 PM, Brian Goetz <brian.goetz at oracle.com> wrote:
> 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.
The class documentation for java.lang.Objects currently states "This
class consists of static utility methods for operating on objects.
These utilities include null-safe or null-tolerant methods for
computing the hash code of an object, returning a string for an
object, and comparing two objects." [1] which to me seems to indicate
that it should provide null-safe or null-tolerant versions of the
methods on java.lang.Object where there is a sensible response (what
would Objects.getClass(null) return?). The obvious APIs for comparison
are Guava's Objects [2] and Apache Commons Lang's ObjectUtils [3].
It seems to me that the java.lang.Objects#nonNull [1] method which
throws NullPointerException for a null argument belongs more in a
preconditions [4] or validation [5] API.
As for null-safe or null-tolerant handling of common types with
defaults, almost every Java project I've ever seen has written or uses
another library method to convert null string to blank, null to empty
arrays or collections, etc. You have to ask yourself if providing
utility methods to handle these null returning APIs is worth the cost
of putting in java.lang, and how far do you go?
- Dave
References:
[1] http://download.java.net/jdk7/docs/api/java/util/Objects.html
[2] http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Objects.html
[3] http://commons.apache.org/lang/api-3.0-beta/org/apache/commons/lang3/ObjectUtils.html
[4] http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Preconditions.html
[5] http://commons.apache.org/lang/api-3.0-beta/org/apache/commons/lang3/Validate.html
More information about the core-libs-dev
mailing list