Singleton and why to avoid it
- Lesson 9 of 32
- 10 min
- Beginner
- 13 steps
A Singleton makes sure a class has a single instance that any part of the code can reach. It sounds handy, but that global access hides dependencies and makes tests step on each other.
- Config instances
- 1
- Hidden dependencies
- 0
- Tests
- —
- request
- response
- failed request
Step 1 of 13
Problem
Every module creates its own configuration
Your app reads its configuration (environment, URLs, flags) from process.env. Orders, payments and email each call new Config(), and in this example there are 10 modules like that: 10 identical objects in memory.
As long as nobody changes them, nothing happens. But if one module changes a value, the other 9 never find out: each one sees its own version of the configuration.
Step 2 of 13
Concept
Singleton: one instance and global access
The Singleton pattern, one of the 23 in the book by Gamma, Helm, Johnson and Vlissides (1994), promises two things: a class has exactly one instance, and any part of the code reaches it through a global access point.
There is no new Config() in each module anymore: they all ask for Config.get() and get the same object. If one changes a value, the others see it.
What changed
- 10 copies of Config
- 1 shared instance
- new Config() → Config.get()
Step 3 of 13
Technique
A private constructor and a static method
The constructor is private: outside the class, new Config() does not compile. The only way in is the static method get().
get() creates the instance the first time (??= assigns only when the field is empty) and returns that same one from then on. That is why Config.get() === Config.get() is true.
Step 4 of 13
Concept
Runtime: a singleton in Java's standard library
In Java, every application has a single instance of Runtime, which connects your program to the environment it runs in. You get it with Runtime.getRuntime(), and the documentation states that an application cannot create its own.
Here uniqueness makes sense: your process runs in one environment, so two Runtime objects would not stand for anything real.
Step 5 of 13
Concept
In Node, a module that exports an object is already a singleton
Node caches every module the first time it loads it. If orders.js, payments.js and email.js call require("./config"), all three get the same object and the file does not run again.
No class, no private and no get(): exporting an instance from a module gives you, in practice, a singleton. With the same costs you will see in a few steps.
Step 6 of 13
Problem
The cache tells modules apart by their resolved filename
Node's cache is keyed by the resolved filename. If two require calls resolve to different names, Node loads the module twice and you get two instances.
The Node documentation gives this example: on a case-insensitive file system, require("./config") and require("./Config") point to the same file but return two different objects. The same can happen with a package resolved from different node_modules folders.
What changed
- Second instance: Config.js
- Instances: 1 → 2
Step 7 of 13
Problem
The signature does not say what the function needs
greeting() takes nothing, but inside it calls Config.get(). Whoever reads its signature, or tests it, has no way to know it depends on the configuration.
With global access, any function can depend on anything without declaring it. In this example, orders, payments and email add up to 3 hidden dependencies: to find them you have to read all their code.
What changed
- 3 dependencies that appear in no signature
Step 8 of 13
Problem
Two tests share the same instance
Now Config has a field that changes: debug. Test A sets it to true and does not restore it. Test B expects false and fails, even though the code it tests is fine.
The failure depends on order: B passes on its own and fails if A runs first. Since both share the only instance, one test's state leaks into the next.
What changed
- Mutable field debug
- Test B fails depending on order
Step 9 of 13
Trade-off
When it makes sense and when it does not
It makes sense when uniqueness is a fact of the environment, like the Runtime of a Java process, and the object holds no state your tests will change.
In application code you rarely need it: having one instance does not require the Singleton pattern. Creating one at startup and passing it to whoever needs it is enough. Avoid it above all when it holds changing state.
Step 10 of 13
Solution
One instance, created at startup and passed as a parameter
The Config constructor is public again. main.ts creates one configuration at startup and passes it to orders, payments and email through their constructors.
There is still a single instance, but now each class declares that it needs it: hidden dependencies drop from 3 to 0. The place where everything is wired is called the composition root; you will see it in the next lesson, dependency injection.
What changed
- main.ts creates the instance
- Config.get() → constructor parameter
- Hidden dependencies: 3 → 0
Step 11 of 13
Solution
Each test passes its own object
greeting() now takes anything that fits the Settings interface. In the app you pass the instance main.ts created; in the test, an object literal { env: "test" }.
Each test builds what it needs and nothing is shared between tests: order stops mattering and test B is green again.
What changed
- Settings interface
- Test object: fake
- Tests: red → green
Step 12 of 13
Concept
NestJS and Angular: singleton by default, but injected
In NestJS, a class marked with @Injectable() is a provider: by default, the Nest container creates one instance and shares it with every class that asks for it in its constructor.
Angular does the same with @Injectable({ providedIn: 'root' }): one instance for the whole app, which you request with inject(). You get uniqueness without global access, and since the dependency comes from outside, a test can pass another one.
Step 13 of 13
Summary
One instance, yes; global access, better not
A Singleton ensures a single instance with a private constructor and static access such as get(). You see it in Java's Runtime.getRuntime() and in any Node module that exports an object.
Its cost is global access: dependencies that appear in no signature and state that leaks between tests. If you need one instance, create it at startup and pass it as a parameter, or let your framework inject it.
← → step · R replay · Space pause
You will learn
- How a Singleton guarantees a single instance (covered)
- Where you meet it: Java's Runtime and Node modules (covered)
- Why global access breaks your tests (covered)
- When it makes sense and when it does not (covered)
- The alternative: create one instance and pass it (covered)