Part 5 of 6 · 2 min read
The downsides
Hidden dependencies and hard tests.
Why many people avoid it
EJ warns that a singleton can make its clients hard to test. A test cannot swap in a fake for the singleton unless the singleton implements an interface that serves as its type. Code that calls Config.INSTANCE deep inside a method has a hidden dependency: nothing in its signature says that it needs the config.
EJ Item 5 makes a related point. Static utility classes and singletons are a poor fit for classes whose behaviour depends on an underlying resource. The better habit is to pass the resource in. This is dependency injection (module 6 of this level), and it connects to Level 2, module 5.
interface Clock { long now(); }
class Service {
private final Clock clock;
Service(Clock clock) { this.clock = clock; }
long stamp() { return clock.now(); }
}
A test creates new Service(() -> 5), and stamp() returns 5. No global is touched. In the real program, main creates one real clock and passes it everywhere. The program still has a single clock, but the class no longer enforces it, and nothing is hidden.
This is the usual modern answer: keep one instance by how the program is wired, and not by a rule inside the class. Use the singleton pattern itself only for things that are unique by nature and stateless, or when a framework forces it.
In an interview, show that you know both sides. Write the enum or holder version when asked for a singleton, then say that you would normally inject it to keep the code testable.
Interview angle
Answer in your head first, then open it.
How do you write a thread-safe singleton in Java?
Use a single-element enum, or eager initialization, or the holder idiom, or a synchronized accessor.
What is wrong with singletons?
They act like hidden global state, so classes depend on them without saying so, and tests cannot replace them easily.
What do you do instead?
Create one instance at start-up and pass it in through constructors.
Check yourself:
1. What does new Service(() -> 5).stamp() return?
2. What does EJ say makes singletons hard to test?
Words you will meet
| Word | Meaning |
|---|---|
| Singleton | A class with exactly one instance |
| Lazy initialization | Creating the object on first use |
| Eager initialization | Creating the object when the class loads |
| Holder idiom | A nested class that holds the instance and loads on demand |
| Global state | Data reachable from anywhere in the program |