Globals and side effects

Martin McBride, 2017-03-21
Tags none
Categories none

You may have been told to avoid global variables. This is good advice in many cases, but there are times when global variables are necessary and useful.

What is a global variable?

Many programming languages allow for both global and local variables:

  • A global variable is defined outside of any function definitions. Global variables can be accessed from anywhere, inside or outside of ant=y function.
  • A local variable is defined within a function definition. It can only be accessed by code within the function.

Global variables can be easier because they can be accessed from anywhere - this means you don't have to think about each of your variables and decide where it should be defined, and how to make it accessible within each function that needs to use it.

The problem is that, because it can be accessed from anywhere, there is nothing to stop a function from changing a variable that it shouldn't really need to change, causing an unexpected side effect. This can create bugs that are very difficult to track down.

When you only use local variables, you are forced to think more about the design of yours software, which might take a little longer but makes your software better and more reliable in the end.

Global constants

Global constants are a special case. Since they are constant, they can't be accidentally altered and cause unexpected side effects.

Global constants are a good thing and you should use them! See more in the section on [variables and assignment](\gcse\programming-techniques\variables-and-expressions\variables-and-assignment).

When you can use globals

While there is always a risk in using global variables, it is sometimes a risk worth taking.

For example, suppose you are writing a game. You might have a game object that stores all the important game information - the score, player lives, what level you are on, etc. This game object might be used in many places in your code, you might decide that it is a lot easier to store the game object in a global variable. This might be justified because:

  • It will simplify your code quite considerably.
  • There should be no confusion, the game can only ever have one game object.
  • It should be obvious to any programmer that you shouldn't randomly replace the game object in the middle of the game.
  • If you do make a mistake, it should show up very quickly.

There is quite a low risk of introducing bugs by using a global game object, so you might consider this as a way to simplify the code, especially for a simple game like space invaders.

Copyright (c) Axlesoft Ltd 2021