I'Ve Heard Global Variables Are Bad, What Alternative Solution Should I Use

I've Heard Global Variables Are Bad, What Alternative Solution Should I Use?

The primary reason why global variables are discouraged in javascript is because, in javascript all code share a single global namespace, also javascript has implied global variables ie. variables which are not explicitly declared in local scope are automatically added to global namespace. Relying too much on global variables can result in collisions between various scripts on the same page (read Douglas Crockford's articles).

One way to reduce global variables is to use the YUI module pattern. The basic idea is to wrap all your code in a function that returns an object which contains functions that needs to be accessed outside your module and assign the return value to a single global variable.

var FOO = (function() {
var my_var = 10; //shared variable available only inside your module

function bar() { // this function not available outside your module
alert(my_var); // this function can access my_var
}

return {
a_func: function() {
alert(my_var); // this function can access my_var
},
b_func: function() {
alert(my_var); // this function can also access my_var
}
};

})();

now to use functions in your module elsewhere, use FOO.a_func(). This way to resolve global namespace conflicts you only need to change the name of FOO.

What is wrong in using global variables?

Global variables work just fine as long as you are writing all the code yourself, and only for yourself.

In web pages there are very often more than one script used. If they use global variables, they can conflict with each other. The less they add to the global namespace, the smaller the risk is to conflict with other scripts.

Why shouldn't I use global variables in JavaScript for something that's constant?

You can use globals if they are protected in what you think is a unique namespace and are only used when beneficial. The main issue is that globals can make one piece of code more likely to conflict with some other piece of code (if not using different namespaces or very unique names). For this reason and others, it is best to avoid globals when they are not actually needed (when variables declared local to some scope would work just as well), but there are still some appropriate reasons to have globals. The main point of education is that many people use globals when they are simply not needed. If you need them or find they are more efficient, then you can use them just fine as long as you protect the namespace from accidental collision.

I personally create one top level, global object and hang all my other globals off that one object.

Some other issues with globals:

  1. They are slower to access in Javascript than locals because they are the last ones found as the interpreter looks for a given variable name in the various scopes that it might exist in. Usually not a noticeable problem, but something to be aware of. Here's a jsperf that shows how much of a difference there can be.
  2. If you have any asynchronous code that modifies globals or timer-driven code that modifies globals and more than one asynchronous operation can be in flight at the same time, the multiple async operations can step on each other through the modification of the same globals.
  3. Globals are often not declared near the point of use so reading code can be more challenging.
  4. Globals are generally not shown automatically in the debugger (the way local variables are) making debugging a little less convenient.
  5. IE automatically defines a bunch of global variables based on some names in the DOM which can conflict with your own global variables without you realizing it.
  6. A simple omission of the keyword "var" on a local variable makes it a global variable and can confuse the heck out of code if that name is already being used as an intended global variable. I've seen this happen on the for (i = 0; i < m.length; i++) construct before. It can be tough to track down what is wrong.
  7. Global variables persist for the life of the script. If one is using a global variable to hold an object reference for something that doesn't need to exist for the life of the script, this can cause the script to use more memory than it otherwise would.
  8. Global variables in a browser exist in the scope of the window object so they can conflict not only with other globals, but also anything else on the window object.

Is using a global user variable a bad practice?

If you use a global variable, you are creating a dependency on that variable in all the modules that use it. So, for example, if you wanted to reuse any of those modules in another project, you would need to take their use of this global variable into account.

Having said that, I don't particularly find it bad design to have a global variable for a user-id. If you wanted to reuse any of the modules that use it, you would want to deal with users anyways, and will probably have that global variable in your new application too.

There are dependency-injection frameworks that could solve this for you. Whether they will add value to your specific project or not depends on many other considerations, and it is really up to you.

Why are global variables considered bad practice? (node.js)

Global variables are considered an anti-pattern in almost any programming language because they make it very hard to follow and debug code.

  • When you browse the code, you never know which function sets or uses a global variable. When all variables are either local or passed to a function, you can be sure that the side-effects of the function are limited.
  • Global variables work at a distance. Screwing with the value of a global could have unexpected effects in a completely different part of the application. When you debug an error caused by that, you will have a very hard time finding out where the variable was changed to a wrong value.
  • Global variables share a namespace, so you can inadvertently reuse them although you don't intend to do so.
  • It's hard to tell how important a global variable is. You never know if it's used by just two functions or if its value is important all over the place.
  • ...and many more reasons...

When you have two modules which share data, you should create an object with that data and explicitly pass it to each function which needs it (and only those which actually do).

Constant Functions Over Global Variables?

You still have a global variable (and it is a variable, not a constant), the only difference is that the value of that variable is a function.

There are no benefits, and you have the overhead of calling the function whenever you want to get the value.

If you want a constant, then use a constant.

const foo = 42;

This still has the drawbacks of being a global and you should still aim to define your variables and constants in as narrow a scope as you can.

Global varaibles are bad, but are used by default in Python

A global variable is a named variable whose value can be reassigned from any scope. In order to reach into a higher scope and reassign a variable that was defined there, you need to explicitly use the global or nonlocal keyword. For example:

def function():
global foo
foo = 5

foo = 3
function()
print(foo) # prints 5

Variables are not global by default:

def function():
foo = 5

foo = 3
function()
print(foo) # prints 3

In your example, the variable dic is not itself being modified, but rather the value that it references (this is possible because dictionaries are a mutable type of value; you can modify the contents of a dictionary via the [] operator). If we try to modify the variable dic inside the function, this change is not reflected in the outer scope:

def function():
dic = {'one': 35}

dic={}
function()
print(dic) # prints {}


Related Topics



Leave a reply



Submit