liveBook · Manning

Null object pattern

As explained in Fabulous Adventures in Data Structures and Algorithms

The null object pattern represents the absence of a value with a valid object that provides appropriate behavior instead of a null reference.

The null object pattern represents an absent value with a valid object that supplies appropriate behavior. For an immutable stack, an empty stack replaces a null reference and implements the same interface as a nonempty stack. section 2.2

An immutable stack applies the pattern through a small set of deliberate choices:

  • Represent the empty stack as a singleton, because there is logically one empty stack. section 2.2
  • Place empty and nonempty behavior in separate classes implementing a common interface. section 2.2
  • Let enumeration of the empty object yield no elements, so iteration ends naturally. section 2.2

Shared empty tail

Starting with ImStack<int>.Empty, pushing 10 and then 20 produces [20, 10]. Popping twice returns []; branching from the same stack permits [20, 10] and [30, 10] to share their tail.

How Fabulous Adventures in Data Structures and Algorithms covers it

How deep it goes
Builds a C# immutable stack with singleton, interface, exception, enumeration, and shared-tail behavior.
Examples
Uses an empty immutable stack, Push and Pop branches, enumeration, and printed stack representations.
What it assumes
Assumes interfaces and object-oriented design while teaching the empty-state representation through a linked immutable stack.
What you can do after
Builds an immutable C# stack that avoids null empty-state references and shares unchanged tails.
How it connects
Connects null handling with immutable data structures, linked lists, singleton objects, interfaces, and object-oriented design.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Fabulous Adventures in Data Structures and Algorithms. The section links point to the parts of the book it draws on.