“Why Developers Fail” Reason #2: Making Use Of Global Variables
In my previous post of the “Why Developers Fail” series, I dealt with all those things that most of us programmers tend to get wrong from time to time. It was specifically focussed on writing code that is difficult to read. The topic for today’s discussion is the use of global variables.
Global variables: Causing trouble for developers since time immemorial
Developers, who by this time have some years of experience behind them, will probably be able to relate to the times of classic ASP 3.0 or Visual Basic 5.0. The main problem of those languages included the use of global variables. These are the variables that can be accessed from any part of the code.
Not all is bad about Global variables…
The global variables, however, have a good side to them as well. They allow you to access their content at any point of time and from practically anywhere in the given lines of code, thus making them a great option for sharing information. Their downside, though, is very much the same: since they can be accessed from anywhere it is very difficult for the developers to pin-point their value.
…but you can never call them “good”
Very often developers make use of a global variable and work under the assumption that it has a specific value contained within itself. You may also assume that it is in a specific state as per the expected order of execution. However, it is unlikely that you will ever know from which part of your code or owing to what circumstances they have undergone a modification. As a result, they are a disastrous failure just waiting to happen.
Modern languages and global variables
If you think that in the modern development scenario we are way past this problem, and that some of the modern programming languages such as C# do not have this issue surrounding them, then it is advisable that you sit down and think again! Have you ever taken the static variables into consideration? What about all those Singleton type objects? And need I make special mention of the application variables and caches present in the web applications? All of these various mechanisms for sharing information can lead to the same problems being produced.
What I would like to advice
If you would like to follow my advice, try and avoid sharing information globally. Yes, if it is strictly necessary then you don’t have a go but otherwise, try and avoid it at all costs. Also, if you do come across one such unavoidable situation, first check the storage of your desired piece of information (whether it is a static variable or a global one does not really hold much meaning) to ensure that it contains what is expected of it to contain. More importantly, see to it that the variable is initialized.
While they look seemingly harmless, they can be unwittingly dangerous. This holds true even when you are testing the developed web applications. So be careful when you work!