Part 6 in a Series by Robert Konigsberg, Guest blogger...
In the first episode, Jesse talked about the Preconditions class. That's not the only mechanism supplied by the Google Collections library for data validation. We're going to look at Objects.nonNull(T) and, by association, Objects.nonNull(T, String).
Objects.nonNull accepts an object, and throws a NullPointerException if it is null. Otherwise it returns the value passed into the method.
Objects.nonNull is wonderfully useful in constructors. Since any use of super in a constructor must be the first statement in the method body, Preconditions can't be used. before the superclass initialization. The Precondition can be used after the superclass initialization, but that doesn't work very well; it forces initialization prior to validation, and besides, Preconditions have a semantic inference; they're meant to be used as pre-conditions, not post-conditions.
Before:
public ConnectAction extends Action {
private final Connector connector;
public ConnectAction(ContextManager mgr, Connector connector) {
super(mgr);
Preconditions.checkNotNull(mgr);
this.connector = connector;
}
public void run(ActionArguments args) { ... }
}`</pre>
### After:
<pre class="prettyprint">`public ConnectAction extends Action {
private final Connector connector;
public ConnectAction(ContextManager mgr, Connector connector) {
super(_Objects.nonNull(mgr)_);
this.connector = connector;
}
public void run(ActionArguments args) { ... }
}`</pre>See? Objects.nonNull operate like a filter within an expression, whereas Preconditions do not.
Objects.nonNull also works well when supplying a large number of arguments:
### Before:
<pre class="prettyprint">`public Person(String givenName, String familyName, Address address, Phone phone, String email) {
Preconditions.checkNotNull(givenName);
Preconditions.checkNotNull(familyName);
Preconditions.checkNotNull(address);
Preconditions.checkNotNull(phone);
Preconditions.checkNotNull(email);
this.givenName = givenName;
this.familyName = familyName;
this.address = address;
this.phone = phone;
this.email = email;
}`</pre>
### After:
<pre class="prettyprint">`public Person(String givenName, String familyName, Address address, Phone phone, String email) {
this.givenName = Objects.nonNull(givenName);
this.familyName = Objects.nonNull(familyName);
this.address = Objects.nonNull(address);
this.phone = Objects.nonNull(phone);
this.email = Objects.nonNull(email);
}`</pre>
Another interesting use of Objects.nonNull is as a post-condition operator:
### Before:
<pre class="prettyprint">`public V get(K key) {
V value = map.get(key);
if (value == null) {
throw new NullPointerException();
} else {
return value;
}
}`</pre>
### After:
<pre class="prettyprint">`public V get(K key) {
return Objects.nonNull(map.get(key));
}
So, when should you use Preconditions.checkNotNull and Objects.nonNull? There's a soft answer: see what feels right. You're a smart programmer, I'm sure.