Global Variables

Started by
11 comments, last by SunTzu 17 years ago
This may be dumb but I am a newbie programmer. Is there a reason to avoid global variables? If not then what is the purpose of access specifiers in classes?
Wanna help spread Firefox? http://www.spreadfirefox.com/?q=user/register&r=126078
Advertisement
Here's a recent thread about some globals advice.

http://www.gamedev.net/community/forums/topic.asp?topic_id=440713&PageSize=25&WhichPage=1

Might not be what your looking for as the guy's application I'm sure is different from what you might be doing, but the examples and advice give some good tips.

I read through it recently and there are some good people in there, that made some of it very clear.
----------------------------------------Now just hit that link that says 'Rate This User' [wink]
It is good practice to restrict access to data to classes that use that data. You then call functions on the class to change/retrieve the data. This encapsulates the data and helps keep to a good clean design.
Web:HexAttack Email:Admin@hexattack.com
Admin [HexAttack
Global variables...

...make the program more rigid (make change difficult).
...make it harder to maintain.
...make it harder to understand.
...make it harder to debug.
...make it harder to reuse code.

When you let any part of a program access something, you basically loose control over it. If some bug arises, you'll have to think of the whole entire program, not just a small sub-section since the entire program can alter that variable. If you want to change that variable, you'll be forced to make changes all throughout your code, making it more difficult and more error-prone. Your code is harder to understand since anything, anywhere could be changing the variable so you can't think about just a small bit at once. If a later program (or later part of the same program) needs similar functionality, you're going to have a tough time separating that part, since the entire code base depends on that variable.

That's not to say that global variables are always the worst choice. Sometimes there is no good alternative. But use them with caution. Their affects become much more prevalent once your programs become much larger.

(Isn't there a C++ FAQ Lite section on global variables? I thought there was, but I can't find it.)
Thanx a lot guys.
Wanna help spread Firefox? http://www.spreadfirefox.com/?q=user/register&r=126078
That is not entirely true. A global variable that is used only in 5 different places does not make the code that much more difficult to maintain especially if it saves the developer from creating some ugly object oriented scheme to simulate the same effect. The key to using global variables effectively is simple:
1) use hungarian
2) know how to use a text search
3) use const and accessor methods



Quote:Original post by Ezbez
Global variables...

...make the program more rigid (make change difficult).
...make it harder to maintain.
...make it harder to understand.
...make it harder to debug.
...make it harder to reuse code.

When you let any part of a program access something, you basically loose control over it. If some bug arises, you'll have to think of the whole entire program, not just a small sub-section since the entire program can alter that variable. If you want to change that variable, you'll be forced to make changes all throughout your code, making it more difficult and more error-prone. Your code is harder to understand since anything, anywhere could be changing the variable so you can't think about just a small bit at once. If a later program (or later part of the same program) needs similar functionality, you're going to have a tough time separating that part, since the entire code base depends on that variable.

That's not to say that global variables are always the worst choice. Sometimes there is no good alternative. But use them with caution. Their affects become much more prevalent once your programs become much larger.

(Isn't there a C++ FAQ Lite section on global variables? I thought there was, but I can't find it.)


Quote:Original post by SoftwareGuy256
That is not entirely true. A global variable that is used only in 5 different places does not make the code that much more difficult to maintain especially if it saves the developer from creating some ugly object oriented scheme to simulate the same effect. The key to using global variables effectively is simple:
1) use hungarian
2) know how to use a text search
3) use const and accessor methods

And 4) don't listen to people who recommend hungarian notation. And yes, a global varliable does make the code more difficult to maintain ,even if it's only used in 5 places.
And, uh.... you should be able to maintain your code without relying on text search.
use hungarian? Someone is going to get confused and think that you mean to put things like dw and sz on variables which is very bad practice in languages with static type systems. Hungarian is meant to supplement the compile-time type system. C++ has a pretty comprehensive type system, unlike assembly. Doing stuff like BackgroundColor is still good though.
On their own, global instances (of which global variables are an example) cause no problem at all, neither at the design level nor at the code level. However, code which acesses global instances, or relies on their existence, can easily become extremely difficult to maintain, refactor or reuse.

Good modular design relies first and foremost on encapsulation: the outside world should not know what the implementation of an entity looks like, and the implementation of an entity should not know what the outside world looks like. The only interaction between the two should be the signature of the entity (a public class interface, a function declaration). Since global instances are not part of signatures, they will always break encapsulation when used, unless they are made part of the implementation of the entity, and their existence is perfectly invisible to the outside world. Of course, using global variables this way is perfectly admissible and even encouraged where useful.

As for externally-visible global variables... If done right, the strategy of "No global variables, ever" reduces development time, for three simple reasons:
  • There is no requirement to think about whether the instance should be in some way global or not. This means that the strategy will result in faster development than deciding on a per-entity basis if that entity should be made global or not, because such decisions take time.
  • The approach does not consist in "passing down the instance to where it's required, instead of making it global", because there is no such thing as "the instance" (which would imply that the instance is global, the point here being that it shouldn't be). The emphasis is instead on "receiving an instance to be used", which decreases mental coupling: we don't care where the provided instance came from, or how the world works.
  • The argument of "having to pass the instance around in many places" is tempting, but how often does this happen? A game creates an input object and passes it to the player. A game creates a renderer, and passes it to a player and level, the latter passes it polymorphically to any other world entities. In most situations, this represents five or six additional arguments to be passed in total, and all of them make semantic sense. The time taken to write these six passes is far smaller than prepending a hungarian prefix to the variable name.
In C and C++ they also carry a performance penalty compared to other variables. Since the compiler can't make any assumptions about aliasing with global variables the compiler can't copy the variable to a register when looping.

Consider a for loop:
int count_G; // our global

for( size_t i = 0; i < 10; ++i)
count_G++;

Normally the value of count_G would be maintained in a register for the entire loop but since its global for each loop the compiler must pull the value from main memory, copy it to a register, modify it, and then copy it back to main memory.

It really can kill performance, especially in tight loops:)

Cheers
Chris
CheersChris

This topic is closed to new replies.

Advertisement