Using global variables - really so bad?

Started by
19 comments, last by rip-off 10 years, 5 months ago
It is almost impossible to unit test code that relies on mutable global state, and where it is possible it is usually annoying.

Another issue is that a global makes it very easy to create what would otherwise be considered insane dependencies between distinct subsystems.

Of course, what is the argument for globals, and is it compelling? The most common is it is inconvenient to pass references to these objects everywhere. Of course, this raises two immediate counter arguments. The first is that if the would-be global is really used nearly everywhere, then your project is spaghetti, everything is tightly coupled and there appears to be no modularity. The second if the global isn't used everywhere, then passing to the areas that actually need them probably isn't quite as inconvenient as first thought.

For simple games that beginners make, there are a few approaches that can help. One common issue is that the logic to check for input might end up buried into a Player class, for example. One solution might be to move the logic to check for input away from the player, and to call member functions on the Player class when input is received/

Another is to bundle a few critical systems that really are needed in lots of places (in one game I made, objects to represent the logical and physical game world, the current level, a simple configuration mechanism and the resource caches) together in a context object. This avoids the need to pass several parameters through to the objects that need them. Care needs to be taken with this approach, because if every area of the game has access to the critical objects then nothing has been gained.

This topic is closed to new replies.

Advertisement