Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "global variables are bad" mean?

So I can read from a global variable

def f() :
  print x

And I can also assign it

def g()
  global x
  x = 3

When people say "global variables are bad", do they mean that both reading and assigning are bad, or just assigning is bad? (my impression is that reading is not dangerous)

like image 695
usual me Avatar asked Apr 01 '14 21:04

usual me


People also ask

Why are global variables considered bad?

Non-const global variables are evil because their value can be changed by any function. Using global variables reduces the modularity and flexibility of the program. It is suggested not to use global variables in the program. Instead of using global variables, use local variables in the program.

Are global variables unsafe?

90% of the time, global variables are introduced to save the cost of passing around a parameter. And then multithreading/unit testing/maintenance coding happens, and you have a problem. So yes, in 90% of the situations global variables are bad.

Why global variables are bad in Java?

Using global variables means they are visible to many classes who can manipulate the data then. So you will have to take care of your data is it is widely visible. And if you are using multithreading then you are in trouble as anybody can modify that data, so lots of scope for data getting corrupted.

Why do people hate global variables?

The reason global variables are bad is that they enable functions to have hidden (non-obvious, surprising, hard to detect, hard to diagnose) side effects, leading to an increase in complexity, potentially leading to Spaghetti code.


1 Answers

The problem is not so much "global == bad" so much as "Global mutable state makes it hard to reason about program flow"

To illustrate, imagine this function:

def frob():
    if my_global:
        wibble()
    else:
        wobble()

That is, frob()s behavior depends on state whos nature is not obvious from either the body of frob(), nor from any code that might have called it. You have to try to figure out what changes my_global, and when those changes happen in relation to when frob() is called.

When programming small scripts, this isn't much of a problem, you can see and understand all of the places that the global variable changes, and probably sort out in your head when it changes and when the dependent bits are invoked. In large programs, that's much more effort, to the point that global mutable state is widely regarded as an anti-pattern.

like image 156
SingleNegationElimination Avatar answered Oct 08 '22 05:10

SingleNegationElimination