Why do they say that the use of global variables is bad practice?

Asked

Viewed 117 times

-2

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

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

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

For example:

counter = 0;

 def faz_alguma_coisa():

    global counter
    counter = counter + 1


faz_alguma_coisa()
faz_alguma_coisa()

print(counter) # 2

It is also possible to do this in PHP.

$variable = 1;

function imitando_python()
{
      global $variable;

      $variable += 1;
}

imitando_python();

var_dump($variable); // 2

Through this code I can understand 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 really my thing.

So I’d like to know:

  • Why use global (global variables) would be a bad practice?
  • Is there any case where the use of global would be essential, or there are other best practices?
  • 3

    Duplicate!!!!!!! http://answall.com/questions/925/por-usar-vari%C3%A1vel-global-n%C3%A3o-%C3%A9-a-good-pr%C3%A1tica

  • Everything has a way of being for each type of paradigm used, I believe that there are advantages and disadvantages for each type of language. Using more heavily typed languages for example ensures that there are not as many errors.

1 answer

2

As this covers several languages I will respond 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 the contador2 will overwrite the same variable from contador1.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.