Global variables aren't the problem...

... global mutable state is the problem. Well, global variables are typically global state, so they are still a problem. However, the distinction is still important, since some design changes taken to remove global variables can actually make a program's design worse.

As an example, there was a project1 that, following common examples, used global variables for command-line flags. To address this issue, the project stopped using package flag. Instead, the program was changed so that all parameters came from environment variables (os.Getenv). If anything, this increased the lifetime of that state, and did nothing to reduce visibility. The end result is to change the statically-typed global state to stringly-typed, stringly-named global state. This hides the global state from the linter, but doesn't really fix the problem2.

As an aside, compromising your UI to make your linter quiet is probably not the road to great software.

The goal of eliminating global variables should be to shorten the lifetime of the variables, limit the visibility of the variables, or both. These changes limit the range of code that can interact with the variables, which is where the improved understandability comes, and so why the design could be said to be improved.

Global variables, like any global mutable state, are a problem because they have long lifetimes, and wide visibility. Shifting that state to a different mechanism, without addressing lifetime or visibility, does not really improve design. Unfortunately, design is a little more work than hiding things from the linter.

Bonus

You can use package flag without using global variables.

1

Names hidden to protect the guilty.

2

Programs often treat environment variables as immutable, even if this isn't really the case. However, changing the state from mutable to immutable would be an improvement. So perhaps that was the motivation here.

Join the discussion...