|
|
|
|
|
by es7
1495 days ago
|
|
On the other hand, singletons and global variables can be incredibly useful for writing clear and simple code. As a web and mobile app developer, I find that globals can be useful. Developers will go through extraordinary lengths to avoid making things global, but the truth is that for end-user applications a great deal of the relevant product requirements are essentially singletons. There’s only one active profile and one user and one catalog and one persistence layer. There’s only one DOM and one window. The result is that code which endeavors to make state which is truly shared and global actually shared and global will often be much simpler and less bug-prone, provided that reasonable abstractions are chosen for any mutation and event APIs related to global state. |
|
Globals are appropriate when "there can be only one"; however, I tend to find that's rarely the case. Much more common is "there can be only one at a time"; in which case, dynamic variables are far more useful than global variables. The most obvious example is in tests.