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.
2 comments:
Shouldn't it be up to the super class to check if the argument is null or not?
Yes, but... the case I had in code for this problem was that I needed to vet the parameters for my own class and calling super(null) was expensive.
Post a Comment