3 ms·
How is a globally-scoped closure not a global variable?
by bandrami 2y ago
How is a globally-scoped closure not a global variable?
- robertlagrant 2y agoA function isn't a variable.
- bandrami 2y agoA function can absolutely be a variable. This isn't even an anonymous closure.
- roenxi 2y agoBecause there is no intent, need or reason to vary it. Nearly everything in RAM is technically a global variable to someone who is keen enough. Programming depends on a sort-of honour system not to treat things like variables if it is hinted that they shouldn't and it doesn't make sense to. Otherwise we can all start making calls to scanmem & friends.
- bandrami 2y agoRight but closing over a state with a function and giving that closure a name seems to quack like a duck to me. Maybe it's just because I'm a scheme guy and we're more upfront about this.
- roenxi 2y agoThe situation is ugly because there is global state by design. But I don't see why the fact that the closure is stored in a mutable location would be a concern for you. Can you think of any conditions where someone would modify it? I'm not really seeing it, and I don't know what your alternative suggestion is going to be to stop them technically. I can tell you when someone would modify a counter variable - every time it needs to be incremented. It leaves open a lot of room for bugs in unexpected parts of the code. Gating access behind a stateful function makes doing the wrong thing more expensive.
- bandrami 2y agoI think we're talking past each other here. The issue is that the enclosed state of counter is exposed globally and can be accessed without synchronization. I suppose yes one could also reassign counter to a different function (and you'd need to be aware of that) but my point is that you still need some kind of sync if you're calling counter all over the place, just like you would with a global variable
- roenxi 2y ago> The issue is that the enclosed state of counter is exposed globally and can be accessed without synchronization. Maybe throw up a code example? I don't follow what you're getting at.