Null object pattern

A key purpose of using a null object is to avoid conditionals of different kinds, resulting in code that is more focused, and quicker to read and follow – i.e. improved readability.

One advantage of this approach over a working default implementation is that a null object is very predictable and has no side effects: it does nothing.

In the case of an empty folder, one response may be to throw an exception or return a null reference rather than a list.

It is, however, still possible to check whether the return value is a null object (an empty list) and react differently if desired.

Extension methods can be made to check for null values, thereby freeing code that uses them from ever having to do so.

Note that the example below uses the C# Null coalescing operator to guarantee error free invocation, where it could also have used a more mundane if...then...else.

The null object pattern solves this problem by providing a special NullAnimal class which can be instantiated bound to an Animal pointer or reference.

Note that NOT having a null class at all is an important feature, in contrast to languages where "anything is a reference" (e.g., Java and C#).

This example shows animal objects that display sounds and a NullAnimal instance used in place of the C# null keyword.

In the GNU Smalltalk for example, the class of nil is UndefinedObject, a direct descendant of Object.

Since nil is the empty list in Lisp, the situation described in the introduction above doesn't exist.

In Common Lisp, the object nil is the one and only instance of the special class null.

Unlike Common Lisp, and many dialects of Lisp, the Scheme dialect does not have a nil value which works this way; the functions car and cdr may not be applied to an empty list; Scheme application code therefore has to use the empty?

Attempts to directly monkey-patch NilClass instead of providing explicit implementations give more unexpected side effects than benefits.

[7] Care should be taken not to implement this pattern just to avoid null checks and make code more readable, since the harder-to-read code may just move to another place and be less standard—such as when different logic must execute in case the object provided is indeed the null object.