The company I'm working for has a HUGE class (Globals.m) that is a singleton. It stores mostly a bunch of BOOLs that should go into NSUserDefaults, but there are also pointers to things like videoplayers that belong to various viewcontrollers. I am fairly new to iOS development (and I'm a lowly intern), but I know in my gut that the code smells to high heaven. How can I explain why using a singleton to store all the variables is bad?
Edit: I don't mean singletons are bad, I just mean in this case. Essentially every significant variable in the app is stored in this one instance.
Using global variables causes very tight coupling of code. Using global variables causes namespace pollution. This may lead to unnecessarily reassigning a global value. Testing in programs using global variables can be a huge pain as it is difficult to decouple them when testing.
By using singletons in your project, you start to create technical debt. Singletons tend to spread like a virus because it's so easy to access them. It's difficult to keep track of where they're used and getting rid of a singleton can be a refactoring nightmare in large or complex projects.
While in many or most other programming languages variables are treated as global if not declared otherwise, Python deals with variables the other way around. They are local, if not otherwise declared. The driving reason behind this approach is that global variables are generally bad practice and should be avoided.
The Singleton pattern is basically just a lazily initialized global variable. It ensures that the class has one instance and that instance is globally accessible. However, do not confuse Singleton design pattern with single instances.
A lot of objects in UIKit are singletons. The UIApplication object is a singleton. NSUserDefaults has the standardUserDefaults
singleton. UIDevice currentDevice
returns a singleton.
Just because it's a singleton doesn't mean it's bad. What is bad is when you start tying functionality in other classes to your singleton object, with it so deeply ingrained that you can't alter the singleton or the affected object easily.
I use a singleton to store my non-CoreData object structures. I also define some helper methods for getting the library directory, encoding data, and keyed archiving. So I can reference a master array object wherever I need it, or easily access methods that would otherwise just be copy and pastes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With