Why Singleton Is Usually a Trap
A Singleton fixes two copies that disagree, but it hides what a class needs and lets tests change each other's results; making one object at the start of the app and handing it in keeps one shared object without either problem.
Journeyman · OOP · Updated
After this lesson you can
- Explain why a Singleton makes code hard to test: hidden dependencies and shared state between tests
- Replace a Singleton by creating one object at the start and handing it in
Key takeaways
- A Singleton is a hidden dependency: nothing in new Checkout() says it needs the settings.
- It's shared by everything, including tests, so one test's change leaks into the next: tests pass alone and fail together.
- The fix: make one object at the start of the app and hand it in, often as a constructor parameter. The app still has only one; each test makes its own.
- Handing in what a class needs is called dependency injection, and Pass 4 builds it fully.
Before this: Singleton: Only One, Ever, and constructor parameters.
The Singleton from the last lesson fixed the holiday tax rate. A week later, the bakery's tests start failing. Not every time: only when they run together. Each one passes when it runs alone. The Singleton is behind it, and the fix is a closer look at an idea you met in SOLID in Plain Words: dependency injection.
The symptom: tests that pass alone and fail together
A test is code that runs your code with known inputs and checks the answer. Here are two, written the simple way: each one sets things up, runs checkout, and prints whether it got what it expected. The first checks the holiday rate. The second checks the normal one:
// A test for the holiday tax rate.
Settings.Instance.TaxPercent = 10;
Report("Holiday test", new Checkout().Total(50), 55);
// A test for the normal tax rate. It passes when it runs alone.
Report("Normal test", new Checkout().Total(50), 54);
void Report(string test, int actual, int expected)
{
Console.WriteLine(actual == expected
? quot;{test}: ${actual}, passed"
: quot;{test}: ${actual}, expected ${expected}, failed");
}
class Settings
{
private static Settings? instance;
private Settings() { }
public static Settings Instance => instance ??= new Settings();
public int TaxPercent { get; set; } = 8;
}
class Checkout
{
public int Total(int subtotal) => subtotal + subtotal * Settings.Instance.TaxPercent / 100;
}
Holiday test: $55, passed
Normal test: $55, expected $54, failed
static class Settings {
private static Settings instance;
int taxPercent = 8;
private Settings() { }
static Settings instance() {
if (instance == null) { instance = new Settings(); }
return instance;
}
}
class Checkout {
int total(int subtotal) { return subtotal + subtotal * Settings.instance().taxPercent / 100; }
}
void report(String test, int actual, int expected) {
IO.println(actual == expected
? test + ": quot; + actual + ", passed"
: test + ": quot; + actual + ", expected quot; + expected + ", failed");
}
void main() {
// A test for the holiday tax rate.
Settings.instance().taxPercent = 10;
report("Holiday test", new Checkout().total(50), 55);
// A test for the normal tax rate. It passes when it runs alone.
report("Normal test", new Checkout().total(50), 54);
}
Holiday test: $55, passed
Normal test: $55, expected $54, failed
class Settings:
_instance = None
def __init__(self):
self.tax_percent = 8
@classmethod
def instance(cls):
if cls._instance is None:
cls._instance = Settings()
return cls._instance
class Checkout:
def total(self, subtotal):
return subtotal + subtotal * Settings.instance().tax_percent // 100
def report(test, actual, expected):
if actual == expected:
print(f"{test}: ${actual}, passed")
else:
print(f"{test}: ${actual}, expected ${expected}, failed")
# A test for the holiday tax rate.
Settings.instance().tax_percent = 10
report("Holiday test", Checkout().total(50), 55)
# A test for the normal tax rate. It passes when it runs alone.
report("Normal test", Checkout().total(50), 54)
Holiday test: $55, passed
Normal test: $55, expected $54, failed
class Settings {
static #instance = null;
taxPercent = 8;
static instance() {
if (Settings.#instance === null) { Settings.#instance = new Settings(); }
return Settings.#instance;
}
}
class Checkout {
total(subtotal) { return subtotal + Math.floor(subtotal * Settings.instance().taxPercent / 100); }
}
function report(test, actual, expected) {
console.log(actual === expected
? `${test}: ${actual}, passed`
: `${test}: ${actual}, expected ${expected}, failed`);
}
// A test for the holiday tax rate.
Settings.instance().taxPercent = 10;
report("Holiday test", new Checkout().total(50), 55);
// A test for the normal tax rate. It passes when it runs alone.
report("Normal test", new Checkout().total(50), 54);
Holiday test: $55, passed
Normal test: $55, expected $54, failed
class Settings {
private static current: Settings | null = null;
taxPercent = 8;
private constructor() {}
static instance(): Settings {
if (Settings.current === null) { Settings.current = new Settings(); }
return Settings.current;
}
}
class Checkout {
total(subtotal: number): number { return subtotal + Math.floor(subtotal * Settings.instance().taxPercent / 100); }
}
function report(test: string, actual: number, expected: number): void {
console.log(actual === expected
? `${test}: ${actual}, passed`
: `${test}: ${actual}, expected ${expected}, failed`);
}
// A test for the holiday tax rate.
Settings.instance().taxPercent = 10;
report("Holiday test", new Checkout().total(50), 55);
// A test for the normal tax rate. It passes when it runs alone.
report("Normal test", new Checkout().total(50), 54);
Holiday test: $55, passed
Normal test: $55, expected $54, failed
The normal test is right, and checkout is right. The holiday test changed the one shared settings object, and the change was still there when the normal test ran. Run them in the other order and both pass. That's the worst kind of failing test: one that depends on what ran before it.
Read it as a doctor would:
- The symptom: tests that pass alone and fail together, or pass on one computer and fail on another.
- The cause: shared global state. Everything that touches the Singleton touches the same object, tests included.
- A second symptom, quieter: look at
new Checkout(). Nothing there says checkout needs settings. You find out by reading its code, or when a test fails. That's a hidden dependency: something a class needs that its constructor doesn't mention.
What would you try?
Reset the Singleton at the start of every test. It works, until someone writes a test and forgets the reset, or a new setting is added and the reset doesn't cover it. You're cleaning up after the design instead of fixing it.
Add a way to swap the Singleton for a test copy. It's still one shared object, now with a back door. Two tests running at the same time still fight over it.
The fix: make one, and hand it in
Go back to the third idea from the last lesson: make one settings object at the start of the app, and hand it to everything that needs it. Checkout asks for its settings in its constructor, so its needs are right there in new Checkout(settings). The app makes one object and passes the same one everywhere, so it still has only one. Each test makes its own, so tests can't touch each other's.
Think of a band's sheet music: the bandleader hands each player their copy of the setlist before the show. Nobody wanders off to find "the" setlist taped to a wall somewhere, and a rehearsal can hand out a different one.

// Each test makes its own settings and hands them in.
Report("Holiday test", new Checkout(new Settings(10)).Total(50), 55);
Report("Normal test", new Checkout(new Settings(8)).Total(50), 54);
// The app makes one settings object at the start and hands the same one to everything.
Settings settings = new Settings(8);
Checkout checkout = new Checkout(settings);
settings.TaxPercent = 10;
Console.WriteLine( quot;App: checkout charges ${checkout.Total(50)}");
void Report(string test, int actual, int expected)
{
Console.WriteLine(actual == expected
? quot;{test}: ${actual}, passed"
: quot;{test}: ${actual}, expected ${expected}, failed");
}
class Settings
{
public Settings(int taxPercent) => TaxPercent = taxPercent;
public int TaxPercent { get; set; }
}
class Checkout
{
private readonly Settings settings;
public Checkout(Settings settings) => this.settings = settings;
public int Total(int subtotal) => subtotal + subtotal * settings.TaxPercent / 100;
}
Holiday test: $55, passed
Normal test: $54, passed
App: checkout charges $55
class Settings {
int taxPercent;
Settings(int taxPercent) { this.taxPercent = taxPercent; }
}
class Checkout {
private final Settings settings;
Checkout(Settings settings) { this.settings = settings; }
int total(int subtotal) { return subtotal + subtotal * settings.taxPercent / 100; }
}
void report(String test, int actual, int expected) {
IO.println(actual == expected
? test + ": quot; + actual + ", passed"
: test + ": quot; + actual + ", expected quot; + expected + ", failed");
}
void main() {
// Each test makes its own settings and hands them in.
report("Holiday test", new Checkout(new Settings(10)).total(50), 55);
report("Normal test", new Checkout(new Settings(8)).total(50), 54);
// The app makes one settings object at the start and hands the same one to everything.
Settings settings = new Settings(8);
Checkout checkout = new Checkout(settings);
settings.taxPercent = 10;
IO.println("App: checkout charges quot; + checkout.total(50));
}
Holiday test: $55, passed
Normal test: $54, passed
App: checkout charges $55
class Settings:
def __init__(self, tax_percent):
self.tax_percent = tax_percent
class Checkout:
def __init__(self, settings):
self.settings = settings
def total(self, subtotal):
return subtotal + subtotal * self.settings.tax_percent // 100
def report(test, actual, expected):
if actual == expected:
print(f"{test}: ${actual}, passed")
else:
print(f"{test}: ${actual}, expected ${expected}, failed")
# Each test makes its own settings and hands them in.
report("Holiday test", Checkout(Settings(10)).total(50), 55)
report("Normal test", Checkout(Settings(8)).total(50), 54)
# The app makes one settings object at the start and hands the same one to everything.
settings = Settings(8)
checkout = Checkout(settings)
settings.tax_percent = 10
print(f"App: checkout charges ${checkout.total(50)}")
Holiday test: $55, passed
Normal test: $54, passed
App: checkout charges $55
class Settings {
constructor(taxPercent) { this.taxPercent = taxPercent; }
}
class Checkout {
#settings;
constructor(settings) { this.#settings = settings; }
total(subtotal) { return subtotal + Math.floor(subtotal * this.#settings.taxPercent / 100); }
}
function report(test, actual, expected) {
console.log(actual === expected
? `${test}: ${actual}, passed`
: `${test}: ${actual}, expected ${expected}, failed`);
}
// Each test makes its own settings and hands them in.
report("Holiday test", new Checkout(new Settings(10)).total(50), 55);
report("Normal test", new Checkout(new Settings(8)).total(50), 54);
// The app makes one settings object at the start and hands the same one to everything.
const settings = new Settings(8);
const checkout = new Checkout(settings);
settings.taxPercent = 10;
console.log(`App: checkout charges ${checkout.total(50)}`);
Holiday test: $55, passed
Normal test: $54, passed
App: checkout charges $55
class Settings {
taxPercent: number;
constructor(taxPercent: number) { this.taxPercent = taxPercent; }
}
class Checkout {
private readonly settings: Settings;
constructor(settings: Settings) { this.settings = settings; }
total(subtotal: number): number { return subtotal + Math.floor(subtotal * this.settings.taxPercent / 100); }
}
function report(test: string, actual: number, expected: number): void {
console.log(actual === expected
? `${test}: ${actual}, passed`
: `${test}: ${actual}, expected ${expected}, failed`);
}
// Each test makes its own settings and hands them in.
report("Holiday test", new Checkout(new Settings(10)).total(50), 55);
report("Normal test", new Checkout(new Settings(8)).total(50), 54);
// The app makes one settings object at the start and hands the same one to everything.
const settings = new Settings(8);
const checkout = new Checkout(settings);
settings.taxPercent = 10;
console.log(`App: checkout charges ${checkout.total(50)}`);
Holiday test: $55, passed
Normal test: $54, passed
App: checkout charges $55
Both tests pass, in any order, because each has its own settings. The app still has exactly one settings object, made in one place at the start, and new Checkout(settings) now says out loud what checkout needs.
How it got its name
Handing a class what it needs, instead of letting it find or build it, is called dependency injection, as Dependency Inversion: Depend on the Promise showed with the report card's sender: the settings are checkout's dependency, and the app injects it, which means it passes it in. It's one of the patterns frameworks are built on, and Pass 4 builds it out fully, including the frameworks that do the handing for you. Those frameworks still let you ask for "one for the whole app": they call it a singleton lifetime. You keep the one shared object and lose the trap.
When a Singleton is fine
- When the object holds nothing that changes, such as a fixed table of country codes. If nothing can change, nothing can leak between tests.
- When a framework hands it out for you as one-for-the-whole-app, through constructors, as above.
- When you're reading older code that uses one. You don't have to rip it out today. Hand it in at one new place at a time, and the tests that touch that place get easier.
How often you'll meet it: this trap, often, in older code; this fix, every day in modern apps (our estimate).
Check yourself
2 questions to try on the lesson page.
So what
"Only one" is fine; "reached from anywhere" is the trap. Make the one object at the start, hand it in, and your tests stop depending on the order they run in. It's the first taste of dependency injection, the pattern Pass 4 builds a whole app on.