Friday, August 04, 2006

A refinement on constructor tidiness

Last year I wrote a post about using generics to improve constructor argument checking, Let generics make your Java constructor cleaner. Since then I have refined the example method, asNotNull.

The original:

public static <T> T asNotNull(final T input) {
    if (input == null)
        throw new NullPointerException();

    return parameter;
}

And updated:

public static <T> T asNotNull(
        final T input, final String message) {
    if (null == input)
        throw new IllegalArgumentException(message);

    return input;
}

There are two differences:

  1. I throw IllegalArgumentException instead of NullPointerException. In addition to this being arguably more correct for the semantics of those two exceptions, it is also more useful as I will know that any NullPointerException is because of a call on a null object.
  2. I use a message for the thrown exception—usually of the form "Missing variableName"—to aid in fixing the problem from the stack trace output.

Another reason for the changes are consistency. I make use of other "contract"-based methods such as asNotEmpty, etc., who all throw IllegalArgumentException with an explanatory message. The consistency makes it easier for other programmers to take up the methods into their own code.

No comments: