Friday, June 24, 2005

Let generics make your Java constructor cleaner

I often find myself writing Java constructors like this:

public SomeClass(final SomeType parameter) {
    super(parameter);

    if (parameter == null)
        throw new NullPointerException();
}

when what I really want to write is this:

public SomeClass(final SomeType parameter) {
    if (parameter == null) throw new NullPointerException();

    super(parameter);
}

which is, unfortunately, illegal. But there is a simple solution:

public SomeClass(final SomeType parameter) {
    super(asNotNull(parameter));
}

What is asNotNull(?)?

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

    return parameter;
}

As I generify the input, I am able to preserve the type on output so including calls to asNotNull(T) lose no type information and I need not write casts.

Of course, you can generalize this idea further and provide a family of tests or a more general method which takes an interface as a parameter or even an Exception parameter to change the thrown exception.