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.
