ArticleslgStudy

computer science

Null object pattern

Null object pattern is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Null object pattern rather than just read about it. In short: In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral (null) behavior. The null object design pattern, which describes the uses of such objects and their behavior (or lack thereof), was first published as "Void Value" and later in the Pattern Languages of Program Design book series as "Null Object".

Key takeaways

  • Null object pattern belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Null object pattern to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Null object pattern from memory before moving on to harder problems.

Reference excerpt

In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral (null) behavior. The null object design pattern, which describes the uses of such objects and their behavior (or lack thereof), was first published as "Void Value" and later in the Pattern Languages of Program Design book series as "Null Object".

Description Instead of using a null reference to represent the absence of an object, a null object implements the expected interface but performs no action. This avoids the need for conditional checks scattered throughout calling code, since the null object can be used interchangeably with a real one. For example, code that retrieves a list of files from a folder might otherwise need to check for a null reference or handle a thrown exception when the folder is empty. Returning an empty list instead — a null object — lets the calling code iterate over the result exactly as it would for a non-empty list, with no special-case handling required. The caller can still explicitly check whether the list is empty if that distinction matters for its logic. The pattern is also useful for providing stand-in implementations during testing, such as substituting for a database connection that isn't available in a test environment.

Relation to other patterns It can be regarded as a special case of the State pattern and the Strategy pattern. It is not a pattern from Design Patterns, but is mentioned in Martin Fowler's Refactoring and Joshua Kerievsky's Refactoring To Patterns as the Insert Null Object refactoring. Chapter 17 of Robert Cecil Martin's Agile Software Development: Principles, Patterns and Practices is dedicated to the pattern.

In various languages

C++ A language with statically typed references to objects illustrates how the null object becomes a more complicated pattern:

Here, the idea is that there are situations where a pointer or reference to an Animal object is required, but there is no appropriate object available. A null reference is impossible in standard-conforming C++. A null Animal* pointer is possible, and could be useful as a place-holder, but may not be used for direct dispatch: a->makeSound() is undefined behavior if a is a null pointer. The null object pattern solves this problem by providing a special NullAnimal class which can be instantiated bound to an Animal pointer or reference. The special null class must be created for each class hierarchy that is to have a null object, since a NullAnimal is of no use when what is needed is a null object with regard to some Widget base class that is not related to the Animal hierarchy. 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#). In C++, the design of a function or method may explicitly state whether null is allowed or not.

C# C# is a language in which the null object pattern can be properly implemented. This example shows animal objects that display sounds and a NullAnimal instance used in place of the C# null keyword. The null object provides consistent behaviour and prevents a runtime null reference exception that would occur if the C# null keyword were used instead.

Common Lisp / CLOS In Lisp, functions can gracefully accept the special object nil, which reduces the amount of special case testing in application code. For instance, although nil is an atom and does not have any fields, the functions car and cdr accept nil and just return it, which is very useful and results in shorter code. Since nil is the empty list in Lisp, the situation described in the introduction above doesn't exist. Code which returns nil is returning what is in fact the empty list (and not anything resembling a null reference to a list type), so the caller does not need to test the value to see whether or not it has a list. The null object pattern is also supported in multiple value processing. If the program attempts to extract a value from an expression which returns no values, the behavior is that the null object nil is substituted. Thus (list (values)) returns (nil) (a one-element list containing nil). The (values) expression returns no values at all, but since the function call to list needs to reduce its argument expression to a value, the null object is automatically substituted. This does not apply to Lisp dialect Smalltalk which has a `nil` value distinct from the empty list and false.

Usage In Common Lisp, the object nil is the one and only instance of the special class null. What this means is that a method can be specialized to the null class, thereby implementing the null design pattern. Which is to say, it is essentially built into the object system:

The class null is a subclass of the symbol class, because nil is a symbol. Since nil also represents the empty list, null is a subclass of the list class, too. Methods parameters specialized to symbol or list will thus take a nil argument. Of course, a null specialization can still be defined which is a more specific match for nil.

Scheme 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? or pair? predicate functions to sidestep this situation, even in situations where very similar Lisp would not need to distinguish the empty and non-empty cases thanks to the behavior of nil.

Ruby In duck-typed languages like Ruby, language inheritance is not necessary to provide expected behavior.

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

JavaScript In duck-typed languages like JavaScript, language inheritance is not necessary to provide expected behavior.

Java

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Null object pattern

Start with the simplest possible case. Write down what Null object pattern claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Null object pattern before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Null object pattern ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Null object pattern

In research
Null object pattern appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Null object pattern in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Null object pattern is common in secondary-school and first-year university syllabi. It links to neighbouring topics Software design patterns, so understanding it makes those chapters shorter.
In everyday life
Look for Null object pattern outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Null object pattern” →

How to study Null object pattern in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Null object pattern means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Null object pattern out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Null object pattern in simple terms?

In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral (null) behavior. The null object design pattern, which describes the uses of such objects and their behavior (or lack thereof), was first published as "Void Value" and later in the P…

Why does Null object pattern matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Null object pattern?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Null object pattern.

Tags

  • Software design patterns

Keep exploring