Skip to content Skip to sidebar Skip to footer

Why Are Global Variables Considered Bad Practice? (node.js)

I'm currently face with a problem where I have two modules that I call that need to be able to modify the same variable. I decided to create a global variable called global.APP_NAM

Solution 1:

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).

Solution 2:

You can read from most of the comments and the other answers why is having a global considered bad practice. However, node.js apps are usually ran from a central point, like "app.js", "server.js" or something similar.

In that case, you can keep some sort of "config" (you said you need APP_NAME.users) as a config option to that file. So in "app.js" you have:

var config = {
  myVar: 100
}

If you need to access this variable in some of the modules, pass it as a parameter. Ie. in global file call it as:

varmodule = require('./lib/myModule.js').init(config);

Now your module can have it's init function exported, so that it sets its own local copy of config. Example:

var localConfig = null;
exports.init = function(config) {
  // merge the two config objects here
  localConfig.myVar = config.myVar;
}

Finally, you can have your local code affect the global object with it's private value. Something like this in your module:

exports.modifyGlobalConfig = function() {
  global.myVar = myLocalValue;
}

Your global app.js would then use that method to modify it's global value.

Post a Comment for "Why Are Global Variables Considered Bad Practice? (node.js)"