The Design of Software (CLOSED)

A public forum for discussing the design of software, from the user interface to the code architecture. Now closed.

The "Design of Software" discussion group has been merged with the main Joel on Software discussion group.

The archives will remain online indefinitely.

Reasons for avoiding global variables?

- To conserve memory?
- To minimize programmer error. e.g. accidentally modifying the value on some area of the code.

Is there any thing else?
Sunday, November 13, 2005
To localise scope ... good grief.

Local variables don't have to be globally crossreferenced.
Globals do. This becomes important in largish systems.

Converse to what you may think, globals can conserve memory usage.
Sunday, November 13, 2005
To minimize probability of error and reduce coupling.
Sunday, November 13, 2005
every variable has a natural scope, and when possible you should put it there.  For example you design a new container type.  The container type is global, because lots of code might want to use such a type.  A particular instance of the container used in the implementation of a call to an output function is not global, it is part of that function.

Instead of using rules, or even thinking about the reasons, first start by thinking about the natural choice implementation.  Anything else is an optimization.  Maybe not a speed or memory optimization, but some sort of optimization.  For example using a Get/Set pair when you could just use a public variable you are optimizing for the ability to change implementation.  Now that might be a good optimization to make, but it is an optimization, as it is not natural.
Tom Cahalan Send private email
Sunday, November 13, 2005
1. Globals make it impossible to have threadable code because anyone can change a variable without taking a mutex.

2. Globals make it impossible to have two of something.
son of parnas
Sunday, November 13, 2005
3. So crap goes out of scope so memory gets deleted. Try tracking down "memory leaks" with global variables.
son of parnas
Sunday, November 13, 2005
Many of the principles that are considered "good design" focus on the ability to change the design afterwards.

This can be important after the first version, when someone is trying to understand how the software works to modify it. As a project gets larger and more people work on it, especially new people who may not have been involved in the original design, this issue becomes even more important.

Global variables have some guidelines by which they're used. Maybe variable A is modified by method B, and read by functions C, D, and E which expect it to have a certain type of value. This means that if method B changes, it may need to change the way variable A is stored which could impact functions C, D, and E. Also, multiplied by many variables in a large program, it can get complex to keep track of which functions are supposed to modify which variables, and it can get difficult to manage all the possible side effects of changing them.

An object-oriented design could address this by having variable A actually inside of class B. Class B provides its own method for functions C, D, and E to use, providing the data in a certain form. If the internal storage of variable A changes, as long as class B provides the same method to access the information, C, D, and E don't need to be affected at all.

For something small the difference is trivial, but as it grows the difference is obvious. It's a good habit even for something small, as sometimes small programs evolve into bigger programs...
Monday, November 14, 2005
Other reasons to avoid globals:

1) You may only have one now, but eventually you're going to want more than one. For example, you may only be opening one file now, so you store the file handle as a global variable and all your code references that global. What happens when you want two files open at once?

2) Thread safety. Globals are hard enough to manage when only one thread is accessing them. Multiple threads will typically trash the contents of global variables at the worst time.

3) Reentrancy. Even in a single thread, using a global will often prevent reuse of code further down the call stack. For example, the C standard library has a function called strtok that's used to break a string into tokens. It uses a global variable to store where the current position in the string is. As a result, suppose you're tokenizing a string like this:


A reasonable way to do this would be use strtok twice: the outer level call breaks the string up on ;, the inner breaks the tokens on =. But because of the global, that doesn't work! The inner call to strtok on = will trash the state, and the second time you call strtok on ; the code goes off into the weeds.
Chris Tavares Send private email
Monday, November 14, 2005
I wonder if this is an experience thing.

I've worked on a lot, a lot of code written by others in Perl and in PHP. Neither place much limits on variable scope, yet the programmer can. Perl has strict which imho is a must to use, and warnings.

Beleive me ... if you are handled a project you need to fix/extend and it's in Perl, you'll be darn glad if you it used strict/warnings (doesn't stop you from using globals) and if handed 300 file php application where one file in includes another including another ... well you're in trouble then. But you might get lucky and see some encapsulation and declaration of variables before use with note of purpose if necessary ... Believe me ... after years of working on code you'll appreciate avoiding global variables like the plague they are.
Monday, November 14, 2005
In addition to what everyone else has said, globals make it harder to understand a program. To figure out what could change the value of a global, you have to examine every line of code.
comp.lang.c refugee
Monday, November 14, 2005
Attack vectors. When a variable is global, it can be attacked/changed from anywhere. When a variable is local, it can only be attacked/changed by local code. If a variable has a structurally flawed content, which would you rather debug: the local variable, or the global?
Tuesday, November 15, 2005
Another reason, for C++ coders : global variables, when instances of classes, imply calling constructors, which makes code execute automatically before the program starts. This is not always desirable because you may not want to be executing that code at all (when running unit tests, for example, or when your global is in a DLL that you may load from other applications), or you may want to control the order of initialization of your global objects.

Using accessor functions, you can delay the initialization to the point where you really need the data, and you can make sure other objects get initialized first if they have to.

Those are pretty much the same reasons why you want to get a singleton object through a function call, not through a global variable.
Carl Seleborg Send private email
Tuesday, November 15, 2005
"Another reason, for C++ coders : global variables, when instances of classes, imply calling constructors, which makes code execute automatically before the program starts."

You mean executed before main(), but there is typically a load of startup code called before main() anyway.

But I see your point. :-)
MBJ Send private email
Tuesday, November 15, 2005
Another reason to avoid global variables is to prevent name clashes in the global namespace and to keep the namespace free for variable names for things that really should be in the global namespace, whatever that may be.
Mark Cidade Send private email
Tuesday, November 15, 2005
In C++, it's particularly important to avoid global singleton objects because the order of initialization of globals is not guaranteed. Thus, if global A depends on global B, there is no way to ensure that B will be constructed first.
comp.lang.c refugee
Tuesday, November 15, 2005
IN my opinion, as long as you understand the intricacies of your coding process, using global variables is fine. Use them sparingly, but nonetheless, under the right circumstances, there is nothing wrong with using them.

I think it's rather wasteful to limit the scope of variables used in the same context within separate methods, per se, when one could just use a global variable to represent the value of that variable....
Brice Richard Send private email
Tuesday, November 15, 2005
I use a global configuration variable... a dictionary containing the global application settings. Cfg("foo") = "bar" stuff. It is read-only except during session initialization (when some information about the current session is stored). Is this an appropriate use of a global variable?
Myrddin Emrys Send private email
Thursday, November 17, 2005
globals should be particularly avoided in shared libraries, and if not, given unique names within 'any future possible usage namespace'... which could be a very tricky thing to do. 

This has got to be the main reason that variables with _ as a prefix are reserved.

If you where coding C/C++ on *nix then all your non static stuff is exported for free... it's like an auto global fest! yay!

Thursday, November 17, 2005
All modules that use a global variable become interdependent on each other.  Anything that modifies the value of the global affects everything else that uses it.  In large systems it's not easy to know what are all the other things that use the global.
T. Norman
Saturday, November 19, 2005

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics
Powered by FogBugz