DEV Community

Discussion on: Are global variables bad?

Collapse
 
pdeveloper profile image
PDeveloper

Phrasing the whole issue from the other end, I think one could argue:
It's better to restrict access to mutable data as much as possible.

Otherwise it's easy to lose track of how the state of the application is changing, and reason about the data flow.

Your get_time() example is off, since the point is to not have a mutable global variable. If your alternative variable was NOT Read-Only, you could have hours of debugging at later points in your application. (If the application state would change with multiple calls to get_time(), then it would be bad)

Collapse
 
dwd profile image
Dave Cridland

It's more that code with unknown side-effects is bad. Globals are just a common path to weird side-effects. If you have a global that's mutable, then this seems fine as long as there are strict rules about how and when it can change.

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

I agree, restricting access to mutable data, in particular having a single owner who modifies the data, is a decent starting point. Of course, it also has nuances, but at least it's not as ambiguous as "global variables".

I'm not off on get_time because the question "are global variables bad?" makes no mention of mutability. It's one of those nuances, which is the point I'm trying to make. A read-only global time variable is something we agree that is okay.