top | item 31407383

(no title)

es7 | 3 years 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.

discuss

order

chriswarbo|3 years ago

> 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.

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.

funcDropShadow|3 years ago

> There’s only one active profile and one user and one catalog and one persistence layer. There’s only one DOM and one window.

But --- hopefully --- there are more than one unit/component tests. ;-)

But I agree, there are contexts in which global variables may make sense, e.g. sometimes in an embedded system, sometimes in a short throw away program. As usual, the community of software developers discusses guidelines without clarifying the context or the assumptions they are working with. Since there are almost no universal guidelines for programming those discussion go on forever.

jupp0r|3 years ago

There’s only one DOM and one window. And then you start using web workers, service workers, audio weblets, … Or you want to write tests for your code, or you want to use the same code in a backend node service or with react-native.

tuyiown|3 years ago

Globals are never the good choice. Hidden/ambient dependencies always ends up causing more problems than it solves. Extraordinary lengths are merely passing an parameter through your stack or a tightly controlled context. This requires proper design if you have a lot of things to pass around, it's merely organizing your code dependencies and not hiding under the global carpet.