Why do you often say that using global variables is bad practice? [duplicate]

-2

I'm going straight to the point. In internet tutorials the outside, you always find someone criticizing some, considering it as a "bad practice."

For example, one of them is the use of the global keyword.

As far as you can reach my humble understanding, languages like Python and PHP (if you have more you can quote), accept that.

For example:

counter = 0;

 def faz_alguma_coisa():

    global counter
    counter = counter + 1


faz_alguma_coisa()
faz_alguma_coisa()

print(counter) # 2

You can also do this in PHP .

$variable = 1;

function imitando_python()
{
      global $variable;

      $variable += 1;
}

imitando_python();

var_dump($variable); // 2

For this code I can see that there may be a problem with the scope of the variable.

But to say that something is bad practice simply because a bad thing is not much of my beach.

So, I'd like to know:

  • Why would using global (global variables) be a bad practice?
  • Is there a case where the use of global would be essential, or are there other better practices?
asked by anonymous 06.05.2016 / 15:15

1 answer

2

As this covers several languages I will answer with a simple example in JS:

i = null;
function contador1(){
    for(i = 0; i < 60; i++){
        if((i%5) == 0){
            contador2();
        }
    }
}

function contador2(){
    for(i = 0; i < 60; i++){
        console.log(i);
    }
}

Note that this loop will not work properly because i is global and contador2 will overwrite the same variable as contador1 .

It would be better to have a local variable or to encapsulate so you do not have conflicts.

    
06.05.2016 / 15:29