Are Global Variables Bad

Why are global variables evil?

This has nothing to do with Python; global variables are bad in any programming language.

However, global constants are not conceptually the same as global variables; global constants are perfectly harmless. In Python the distinction between the two is purely by convention: CONSTANTS_ARE_CAPITALIZED and globals_are_not.

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.

However, sane use of global state is acceptable (as is local state and mutability) even in functional programming, either for algorithm optimization, reduced complexity, caching and memoization, or the practicality of porting structures originating in a predominantly imperative codebase.

All in all, your question can be answered in many ways, so your best bet is to just google "why are global variables bad". Some examples:

  • Global Variables Are Bad - Wiki Wiki Web
  • Why is Global State so Evil? - Software Engineering Stack Exchange
  • Are global variables bad?

If you want to go deeper and find out why side effects are all about, and many other enlightening things, you should learn Functional Programming:

  • Side effect (computer science) - Wikipedia
  • Why are side-effects considered evil in functional programming? - Software Engineering Stack Exchange
  • Functional programming - Wikipedia

Why are global variables considered bad practice?

They clutter up the global namespace and are slower to look up than local variables.

First of all, having many global variables is always a bad thing because it's easy to forget you declared a variable somewhere and accidentally re-declare it somewhere else. If your first variable was local then you don't have a problem. If it was global, then it just got overwritten. This gets even worse when you get into implied globals (e.g. when you say someVar = someValue without declaring someVar with the var keyword).

Secondly, global variables take longer for Javascript to "find" than local variables. The difference in speed isn't huge, but it does exist.

For further reading and a more in-depth explanation of why globals are considered bad practice, you may want to check out this page.

Should global variables in javascript be always avoided?

so the reason for to avoid using global variables as much as possible as stated in the previous answers. It is about easily overriding problem and troubleshooting when some global values are being overriden. From my own experience, I usually create an utility to handle sharing values. The idea is as following

//global.js
(function(){
const context = {};
function setGlobalValue(key, value) {
context[key] = value;
}
function getGlobalValue(key) {
return context[key];
}
window.setGlobalValue = setGlobalValue;
window.getGlobalValue = getGlobalValue;
}());
// app.js
function codeAddress(address) {
geocoder.geocode({ 'address': address},
function(response, status) {
if (status == 'OK')
{
var senddata = $.get('/myurl',{params}, function (data){ setGlobalValue('codeAddress', data) });
} else {
}
});
}
// get value here
console.log(getGlobalValue('codeAddress'));

by this way we can track all the global values by searching for setGlobalValue since this is the only way to set "global" value context.

Are global variables in PHP considered bad practice? If so, why?

When people talk about global variables in other languages it means something different to what it does in PHP. That's because variables aren't really global in PHP. The scope of a typical PHP program is one HTTP request. Session variables actually have a wider scope than PHP "global" variables because they typically encompass many HTTP requests.

Often (always?) you can call member functions in methods like preg_replace_callback() like this:

preg_replace_callback('!pattern!', array($obj, 'method'), $str);

See callbacks for more.

The point is that objects have been bolted onto PHP and in some ways lead to some awkwardness.

Don't concern yourself overly with applying standards or constructs from different languages to PHP. Another common pitfall is trying to turn PHP into a pure OOP language by sticking object models on top of everything.

Like anything else, use "global" variables, procedural code, a particular framework and OOP because it makes sense, solves a problem, reduces the amount of code you need to write or makes it more maintainable and easier to understand, not because you think you should.

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

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

D: are global variables bad?

It depends on what you really mean by 'global'. In the example above, I'd say its fine.
You appear to be showing a main module, which probably shouldn't be imported
by anything. In other words, it isn't really global, it is local to the main
module. It really isn't so different from

class Main {
private string _roothtml;
static this() { _roothtml = buildPath(getcwd, "html"); }
void run() { }
}

Even if it isn't really your main, D's
module system offers protections of its
own. Just stick a private on roothtml to encapsulate it within the module
(it wouldn't hurt to do this in your main module anyways, just to be clear).

A pattern like this is widely employed in the source code of git. Rather than
having a single main module that invokes a function for a given command, you
have many main functions -- one for each top-level command.

For example, take a look at
upload-pack.c.

See those variables declared at the top of the source file?
Would the code have been any clearer or safer if they were wrapped in a class in
typical OOP style or of explicitly passed to each function in a more purely
functional style?

Each source file acts as a unit of encapsulation for a given command. This style is not always appropriate, but in the case of a program that can be thought of as a set of distinct commands, it can be cleaner than the alternatives.

Ultimately, the answer will be specific to the context, your given project, and
your personal style. Generally speaking, cross-module globals are something to
be looked on with suspicion, but module-level variables can sometimes be cleaner
than the alternatives.



Related Topics



Leave a reply



Submit