Singleton, Service Locator and Tests in iOS
Article Summary
Bohdan Orlov from Bumble Tech tackles one of iOS development's most controversial debates: are Singletons and Service Locators actually anti-patterns, or just misunderstood tools?
This deep dive from Bumble's engineering team examines why Singletons and Service Locators earn their bad reputation in iOS codebases. The article walks through practical examples of how these patterns break testability and create hidden dependencies, then offers concrete solutions for using them safely.
Key Takeaways
- Hidden dependencies make code untestable: NetworkManager.shared calls can't be mocked in tests
- Service Locators should live only in factories, never in testable business logic
- Eliminate static variables for singletons to make misuse impossible at compile time
- Protocol-based injection turns implicit dependencies into explicit, testable contracts
Singletons and Service Locators aren't inherently bad, but they must be confined to factory layers and injected explicitly to maintain testability.
About This Article
Badoo's engineering team found that lazy initialization of singletons can quietly change application state. This happens when developers depend on side effects like notification subscriptions without managing how long these objects live.
Bohdan Orlov suggests making singleton lifetimes explicit. Keep them running for the entire app, or tie them to key app states like when a user logs in or out. This removes the hidden initialization side effects.
This prevents state from changing in unexpected ways and makes developers think about when singletons actually become available. It cuts down debugging time since you're no longer chasing initialization order problems.