Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
NonNullable.java (see JavaDoc for more info).
import java.util.Map;
import java.util.Set;
/**
* An immutable object reference that may not be null.
* <p>
* This class has two purposes:
* <ul>
* <li>it adds a clearly documents the fact that a variable must not be
* <code>null</code>.</li>
* <li>it helps users to catch possible {@link NullPointerException}s as early
* as possible in the value chain.</li>
* <li>it minimizes the risk of forgetting to check for null values in
* constructors.</li>
* </ul>
* </p>
* <p>
* {@link NullPointerException}s are a misery in Java. Sadly, we have to live
* with them and the best thing to deal with them is doing it as early as
* possible in code. This class aims to help you with this.
* </p>
* <p>
* A note on immutability: This class i immutable/final because is keeps
* hashCode and equals methods to always return the same result throughout the
* life cycle of an instance. This makes is possible to have
* {@link NonNullable}s in {@link Map}s and {@link Set}s etc.
* </p>
*
* @author Jens Rantil <jens.rantil@gmail.com>
*
* @param <V> the type of the real value to hold
*/
public final class NonNullable<V> {
/**
* The real value that this class wraps.
*/
private V value;
/**
* Contruct a {@link NonNullable} immutable.
* @param initialValue the actual value. Must (duh!) be non-null.
* @throws NullPointerException if initialValue is null.
*/
public NonNullable(V initialValue) {
if (initialValue == null) {
throw new NullPointerException("Must not be null: " + initialValue.toString());
}
this.value = initialValue;
}
/**
* Get the actual non-null value.
* @return value of type V. Never null.
*/
public V get() {
return value;
}
/**
* Returns the (unmodified) {@link String} representation of the current
* value.
*
* @return a string.
*/
@Override
public String toString() {
return value.toString();
}
/**
* Returns a hash code value for the wrapped value object.
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return value.hashCode();
}
/**
* Indicates whether some other object is "equal to" the wrapped value
* object.
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
return value.equals(obj);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment