I've seen this piece of code several times on Stackoverflow:
public void doStuff(Object anObject) {
if (anObject == null) {
throw new NullPointerException("anObject can't be null");
}
//rest of the function
}
This is a guard clause against null
parameters because passing null
to a function that requires the argument to be non null will result in a NullPointerException
.
I understand the importance of guard conditions to validate arguments in other cases (i.e. checking date ranges, negative monetary values, invalid string size etc.).
However, in the case of null
specifically isn't throwing a NullPointerException
redundant? How does that differ from letting the Run-time throw a NullPointerException
itself later on?
Note: I'm asking in a language agnostic way since the pattern itself could be applied in both Java and C#.