13 of 22 · System architecture
Services vs Singletons
A singleton is a type with one globally reachable instance (static let shared). A service is a capability behind a protocol that's passed to whoever needs it. You can have exactly one instance of a service without making it global.
How it's wired
- Singletons are global access to one instance.
- A service is a dependency behind a protocol, passed in.
| Part | Owns | Looks like |
|---|---|---|
| Singleton | One global instance | static let shared |
| Service | Capability behind a protocol | protocol ThanksCounting |
| Scope | Who owns the instance's lifetime | App, user session, screen |
Why .shared hurts at scale
- Hidden dependencies: a function that calls .shared doesn't say so in its signature. You find out when a test leaks state.
- Test pollution: shared state survives between tests and makes them order-dependent. Parallel test execution makes it worse.
- Lifetime: a singleton lives forever. Clearing a global cache at logout can race a background save, and user A's data lands in user B's session. Scope user data to a session object that is dropped on logout.
- Migration doesn't need a rewrite: add a protocol, conform the singleton, inject it with a default argument, then move call sites one at a time.
When a singleton is fine
| System-owned services at the edges | FileManager.default. URLSession.shared is fine for simple fetches, but it shares cookies, cache and credentials, so give user-scoped traffic its own configured session. |
|---|---|
| Anything holding user data | Session-scoped, injected. |
Compared
Singleton vs injected service vs session scope
| Singleton | Injected | Session scope | |
|---|---|---|---|
| Testable in isolation | No | Yes | Yes |
| Lifetime | Process | Owner's choice | Login to logout |
| Multiple accounts | Breaks | Possible | Natural |
Expert notes
- One instance is fine. Global access is the problem.
Check yourself
Answer out loud before you reveal. Recall is what makes it stick.
Explain Services vs Singletons in 30 seconds.
- A singleton is one instance reachable everywhere through .shared.
- A service is a capability behind a protocol that gets passed in.
- One instance is fine; global access is the problem: hidden dependencies, state leaking between tests, and a lifetime that never ends, so logout can leak one user's data to the next.
- I keep singletons at the edges and inject anything holding logic or user data.
Singletons versus injected services: what goes wrong with UserManager.shared, and how do you migrate?
- Turn
UserManager.sharedinto an injected dependency. - Singletons are global mutable state, they hide dependencies, and they live for the whole run, which often forces optionals.
- Define a protocol, make the singleton conform with no changes, and inject it, like
init(users: UserManaging = UserManager.shared). - Then migrate one view controller at a time with no big-bang rewrite.
Tests pass individually but fail together because one test logs a user in. What's the root cause, and the fix?
- Shared global state is leaking between tests.
- The singleton survives the whole run and is hard to reset, so test order changes results.
- Inject protocol-typed services, like
init(userService: UserService, logoutService: LogoutService), and build fresh instances in each test. - The tests become isolated, and you can safely run them in parallel.
Some resources should be shared, like an image cache. How do you share them without a singleton's downsides?
- Inject a factory that owns the shared pieces, like the image cache and
URLSession, and have it create fresh objects for per-consumer state. - Every screen then shares the cache but gets its own request queue.
- You keep the benefit of sharing without global access.
- The cost is more types, and someone has to own each instance's lifetime.
- That works because the factory is injected, so each consumer's dependencies stay visible and replaceable in tests.
On logout you clear the image-cache singleton, but user A's thumbnails still show up for user B. What happened?
- An in-flight save wrote A's image into the freshly cleared cache.
- A singleton has no owner and no end of life, so teardown always races with background work.
- Scope user state to a user object that owns the cache and is passed down explicitly.
- Logout drops the whole object graph, work in flight still holds its own user's context, and user B starts clean.
Product now wants two accounts signed in at once, and SessionManager.shared is used everywhere. How do you plan the migration?
- Scope it to the user.
- The real bug is giving session state app lifetime.
- Introduce a
UserSessionobject that owns the session, caches and services, and inject it one flow at a time, starting whereSessionManager.sharedis read. - When you're done, each signed-in account has its own object graph.
- Truly app-wide things, like a shared memory cache, can stay global.
- Because each account's services hang off its own session object, signing one out drops exactly its state.
The AppDelegate holds the API client, the cache and the current user. What test decides what may stay global?
- Apply a three-part test.
- Nothing else owns it, there's exactly one, and it isn't a constant.
- Most data fails, because it has a natural parent like the screen or flow that manages it.
- The API client and current user usually belong to a session object.
- Anything that passes should be self-contained.
- Hide it behind an accessor anyway, so you can swap the implementation later.