Design Patterns
Null Object
Using a null object costs the same O(1) time (a constant amount) as using a real one. The win is fewer scattered checks, not speed.
The idea, in plain English
A null object is a stand-in that politely does nothing, instead of leaving an empty gap. Think of a hotel giving a guest with no special requests a blank preference card that just says 'no requests'. Staff can still read it like any other card, instead of getting confused by a missing card. In code, instead of returning nothing (called null) and forcing everyone to check for it, you return a harmless stand-in object. It safely does nothing when used.
How it works
- 1You design a 'null' version of your object with the exact same methods as the real one.
- 2Instead of doing real work, those methods return a safe, harmless default.
- 3Any code that was going to check 'is this null before I use it?' can skip that check completely, and just call the methods normally.
When you'd use it
Use this when something might not be found — a missing user, an unset logger, an empty cart — and you're tired of sprinkling null checks everywhere before using it.
Common beginner mistakes
- Give the null object every method the real object has, or it can still crash on the one method nobody thought to add.
- Don't use a null object where you actually need to know 'this was missing' for an important decision. That silently hides the fact.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Hello, Alice!
Hello, guest!
Is user2 null object? yesNot sure this is the right topic? See the learning paths → or where this leads →