3 ms·
Global objects need to be initialized. And if two are ever initialized you run into problems like the above. Singleton is a pattern to ensure that a global obj
by dragontamer 2y ago
Global objects need to be initialized. And if two are ever initialized you run into problems like the above.
Singleton is a pattern to ensure that a global objects is only ever initialized once.
- unscaled 2y agoMost programming languages written after 1990 let you initialize global variables lazily. The main problem is that the initialization order might be unexpected or you may run into conflicts. Singletons make the order slightly more predictable (based on first variable access), although it is till implicit (lazy). But singletons are still a terrible idea. The issue with global variables is not just initialization. I would argue it's one of the more minor issues. The major issues with global variables are: 1. Action at distance (if the variable is mutable) 2. Tight coupling (global dependencies are hard-coded, you cannot use dependency injection) 3. Hidden dependency. The dependency is not only tightly-coupled, it is also hidden from the interface. Client code that calls your function doesn't know that you rely on a global variable and that you can run into conflict with other code using that variable or that you may suddenly start accessing some database it didn't even know about. Singleton does not solve any of the above. The only thing it ensures is lazy initialization on access.