hyperoslo / hyperoslo/iOS-playbook
Singleton usage, sharedInstance implementation pattern
- Dominant language
- No language data
- Stars
- 228
- Forks
- 28
- PR merge metrics
- No merged PRs in 30d
Description
Singleton is an abused pattern and often you can achieve similar result by using dependency injection.
**Singleton Abuse**
Example: - `[MYState sharedState]`
Problem with Singleton:
- It's globally available. It's a global variable in a nicer class wrapper.
- It's hard to unit test. The methods that access global singleton need to be mocked
- Unpredictable results, one component can save some data to global singleton and other component wouldn't know that.
``` swift
func fetchResult()-> Int {
MyState.sharedState().result
}
```
For this example I need to mock `MyState.sharedState`
**Solve problem**
Instantiate Singleton in the init or other method and pass it to the method that does the work.
``` swift
func fetchResult(state: MyState)-> Int {
state.result
}
```
In that cases fetchResult doesn't know that MyState is an Singleton and in unit test you can make state object (not Singleton) and pass it.
**Resources :**
http://www.objc.io/issue-13/singletons.html
https://www.youtube.com/watch?v=-FRm3VPhseI&index=2&list=PL693EFD059797C21E
http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.