Re: IllegalArg vs NullPtr Exceptions
Scott A. Hightower wrote:
The question is whether to test for a null argument value and throw an
IllegalArgumentException or to let the inevitable NullPointerException
through and document that it *will* happen.
A related question is whether to test for an empty List passed as an
argument value and throw an IllegalArgumentException or to let
NoSuchElementException through and document that it is *supposed to*
happen.
The utility accepts Lists as arguments to several public methods. The
only thing that it does with each List is get an Iterator from it and
extract the elements of the list for comparison and storage.
I find it really useful to design an API in such a way that preconditions
checking can be done by the compiler as often as possible.
It is not possible to do that in Java with nulls (you could use @NotNull
annotation though). But you can try to make preconditions more explicit
(hence easier for the client to enforce) for empty lists.
Consider something like this:
//the implementation can differ
//I am not sure if such implementation does not
//violate List contract, but...
public class NonEmptyList<T> implements List<T> {
List<T> wrapped;
//convinience
public static NonEmptyList<T> newArrayList(Object first) {
...
}
public NonEmptyList(List<T> wrapped) {
if (wrapped.size() == 0) {
throw new IllegalArgumentException();
}
this.wrapped = wrapped;
}
public boolean remove(Object o) {
if (wrapped.size() == 1 && wrapped.contains(o)) {
throw new IllegalStateException("That would make the list empty");
}
return wrapped.remove(o);
}
...
}
public interface API {
//does not throw IllegalArgumentException in case of empty lists
<T> void operation1(NonEmptyList<T> list)
throws NullPointerException, Operation1Exception;
...
}
Note - I'm not advocating you should do it always - it is just something to
consider.
--
Michal