Boss lesson · Unit 02
Only one
One shared instance, and what sharing it costs
What you practise
- Singletons and module-level state, why global state makes tests and reasoning hard, passing the one instance instead
Try a question from this lesson
Pick one
get() returns the one shared Config; its debug flag starts as false. Run alone, each test passes. What happens when A runs, then B?
def test_a():
get().debug = True
assert get().debug
def test_b():
assert not get().debugfunction testA() {
get().debug = true;
assert(get().debug);
}
function testB() {
assert(!get().debug);
}function testA(): void {
get().debug = true;
assert(get().debug);
}
function testB(): void {
assert(!get().debug);
}Correct answer
B fails: A left the flag switched on
Why
Both tests talk to the same object, and A's change is still there when B looks. B is correct on its own and red in the suite: the tests are coupled through state neither of them owns.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Singleton
A singleton is a class with one shared instance, reached through an access function from anywhere in the program.
It guarantees "only one". It also makes that one object global: any code can read it, any code can change it, and no signature shows who does.
Python noteA module is already a singleton: an object created at module level is the same object for everyone who imports it.
JavaScript noteA value exported from a module is created once and shared by every file that imports it.
TypeScript noteA value exported from a module is created once and shared by every file that imports it.
Concept
One instance, passed around
"Exactly one" and "reachable from everywhere" are separate decisions. You usually want the first and not the second.
Build the one instance at startup and pass it to whatever needs it. There is still a single object, but every user of it is visible in a signature, and a test can pass its own.
9 more exercises in the app
- 3× type the answer
- 1× true or false
- 3× multiple choice
- 1× fill the blanks
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.