I am not a fan of methods that accept null and I can find
very few reasons for ever wanting to return null. Once a null gets into your code it can cause havoc, which is best discovered as soon as possible during development as it either indicates a serious problem or a buggy method returning null under certain circumstances (usually instead of an empty Collection).
How many times have you had to rewrite a simple equals call to allow for a null? The option usually comes down to explicitly doing a != null, and only then performing the check, or writing the equivalent of
"A String".equals(parameter);
which is just plain backwards!
I was very happy when it finally occurred to me that Java 5’s varargs could be used to create this helpful little method
static public void notNull(Object... objects) {
for (Object o : objects) {
if (o == null)
throw new NullPointerException();
}
}
When used as the first line of any method, it catches null parameters before they get lost… otherwise it takes some digging with a debugger to find where they came from. I often wonder if the Java designers shouldn’t have forced all parameters to be non-null, allowing null only if the method declaration had a keyword nullable or something similar.
When is a null parameter acceptable
I don’t think I’ve ever seen a method that accepts null with good reason, although many methods allow it. There are situations that can be forgiven, such as signifying to the method that a default value is fine for this parameter. However, it is often possible to avoid accepting null with good API design and method overloading. Even in the case where null signifies a default value, it is not clear from reading client code what is going on… especially if there are several nulls.
Can anything think of any more?
When is it acceptable to return null
I personally believe that a method should not need to return null where a checked Exception makes sense. If an explicit check for the exceptional case is common, then it may be forgiven… for example when a Map does not contain a key it will return null, but Map.containsKey() provides the explicit check to confirm this since null is actually a valid value (a strange choice in API design, I’m sure they had their reasons because HashTable didn’t allow null keys or values.).
But philosophical belief and practice are two very different things… in reality I often return null instead of throwing an Exception when there is only one exceptional state and the exceptional state is akin to false, e.g. there was no cached solution or it failed for a singularly predictable reason. Yeah, I know, it’s total hypocrisy… but non-public code is ugly by definition
UPDATE: I recently noticed that the Google Collections API (a nice set of useful utilities and classes) has a Nullable annotation
x wrote:
May 7th, 2007 at 10:37 pm