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:
- I throw
IllegalArgumentExceptioninstead ofNullPointerException. 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 anyNullPointerExceptionis because of a call on anullobject. - 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:
Post a Comment