Global variables are dangerous because they can be simultaneously accessed from multiple sections of a program. This frequently results in bugs. Most bugs involving global variables arise from one function reading and acting on the value of a global variable before another function has the chance to set it to an appropriate value.

Global variables also make code difficult to read, because they force you to search through multiple functions or even modules just to understand all the different locations where the global variable is used and modified.

The code below uses global variables and a function to compute the area and perimeter of a rectangle. As you can see, even with two functions it becomes difficult to keep track of how the global variables are used and modified.

One common solution for avoiding global variables is to create a class and store related global variables as members of an instantiated object of that class. This results in more compact and safer code.

In the modified code below, the author eliminates the need for the global variables WIDTH and HEIGHT by encapsulating this data into a class called Rectangle.