Null as return value

Avoid bothering your users with null values – either as value for parameters or as a return value.  With null as return value callers will have to write if cascades to deal with the null values at some point. This makes code both hard to write and read. In most cases null means “empty”, “none”, “not available” or “not yet available” and exactly that should be expressed by other appropriate language constructs.

In the following example GetResult could return null which requires extra logic by the caller:

String result = GetResult();
if (result == null)
{
    result = "prefix";
}
else
{
    result = result.Insert(0, "prefix");
}
Avoid returning null.

 

Do provide an API comment which makes it clear what possible return values of the method are. For example: “Method never returns null”.

 

Generalized not returning null but something “empty” is known as the null pattern. In case a method wants to return a value which expresses “not available” and this is not considered as an error it always should return an object which implements the null pattern.

 

To express empty strings, collections or an enumerable use the corresponding empty string or collection. Namely: String.Empty, new List() or other empty collections and Enumerable.Empty()

 

Sometimes you are in the situation where it indeed plays a role whether the return value is null or empty. For example consider a dictionary of strings as keys and values and a LookUp operation on it. The caller needs to distinguish between the meanings “key not found” and “value is empty”. The latter is expressed by returning String.Empty but then this not available anymore for the “key not found” message for which it becomes tempting to returnnull.

 

When there is a semantic difference between null and “empty” consider introducing a helper structure (or use System.Tuple) to transmit both: A success indicator and in case of success the result value.

Flattr this!

Leave a Reply

Your email address will not be published. Required fields are marked *