Objects.nonNull() (original) (raw)

Brian Goetz brian.goetz at oracle.com
Thu Jan 13 20:06:54 UTC 2011


I relatively recently discovered the existence of the new java.util.Objects class, a repository of useful methods that people end up rewriting endlessly for each project in classes named Util and such. Most of the methods have to do with centralizing null handling (such as Objects.hashCode(), which returns 0 if the object reference is zero.)

I have one concern about naming, and that is of the nonNull(Object) methods:

 /**
  * Checks that the specified object reference is not {@code null}. This
  * method is designed primarily for doing parameter validation in 

methods * and constructors, as demonstrated below: *

      * public Foo(Bar bar) {
      *     this.bar = Objects.nonNull(bar);
      * }
      * 
* * @param obj the object reference to check for nullity * @param the type of the reference * @return {@code obj} if not {@code null} * @throws NullPointerException if {@code obj} is {@code null} */ public static T nonNull(T obj) { if (obj == null) throw new NullPointerException(); return obj; }

Most of the other methods in this class are of the form "do the right thing if the object is null (or an array)", but this one is "throw an exception if the object is null." The intent is clear -- it is for simplifying fail-fast behavior by checking for nullity early -- but the name is wrong. This is bad for two reasons: (a) it is confusing and (b) it forecloses on using the name nonNull() for what most people expect it to do -- which is provide a reasonable default.

I propose to change these to be called checkNonNull(), so their null-checking behavior is obvious to readers of code, and to leave room to LATER provide methods like

public static T nonNull(T[] obj) { return (obj == null) ? (T[]) ZERO_LENGTH_ARRAY : obj; } and public static T nonNull(String obj) { return (obj == null) ? "" : obj; } etc.

It is late but since this class was added in 7, we have a small window to not have to deal with this forever.

Now taking objections. Going once...



More information about the core-libs-dev mailing list