hyperoslo / iOS-playbook

Hyper's iOS playbook
Other
227 stars 28 forks source link

Singleton usage, sharedInstance implementation pattern #139

Open kostiakoval opened 9 years ago

kostiakoval commented 9 years ago

Singleton is an abused pattern and often you can achieve similar result by using dependency injection.

Singleton Abuse

Example: - [MYState sharedState]

Problem with Singleton:

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.

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

3lvis commented 9 years ago

I agree, you can say that 99.99% of the cases using a Singleton is the wrong answer.

As I see it, Singleton is most of the time, a shortcut for understanding the application workflow.

And you shouldn't take that shortcut, it will bite you hard afterwards.