Re: Best practices with globals and subroutine argumentsby gnosti (Friar)
|on Jun 09, 2010 at 09:19 UTC||Need Help??|
I've been following the general disparagement of using global variables on PM for at least a year.
I am especially curious when I read comments (as above) to the effect that global variables are unconditionally poor practice.
Global variables have a respectable place in the annals of computer science. In recent history, the linux kernel is a large project that uses global variables. Linus originally elected this design to avoid the message-passing overhead of a microkernel. That was a technical decision, and kernel programmers seem to be bearing the maintenance burden fairly well. So are the maintainers of billions of lines of COBOL, also no doubt using global variables.
Is the vociferous advocacy against global variables due to module authors' focus on separation of concerns, due to devotion to achieving reliability in large systems or what?
My application, Audio::Nama started with a couple hundred lines of code. Now it has grown to having more than 200 global variables in the package's root namespace.
Some 25 of these variables house widgets related to the Tk GUI. I could take them out of the root namespace and put them in a GUI namespace, but they'll still be globals.
What benefit will I have from rewriting every statement referring to one of these variables?
Configuration and state variables in the global namespace are convenient. The app has a shell that lets me dump variables and data structures at will. I have a useful test suite that helps me track regressions, and use version control to develop new functions. Does the convenience of globals and the inconvenience of other solutions figure into the 'globals are bad practice' calculation?
Things have broken for many many reasons over the five year life of my project. Mistakenly assigning to a global variable may have happened only a couple times, typically when using '=' instead of '==' in a comparison.
Some could criticize my app as being a ball of mud. Certainly high level structures have come gradually. I've only introduced namespaces and classes when confronted with difficulties in reading or maintaining the code that I couldn't otherwise resolve.
Global variables is an area I'm considering, however I am still looking for alternatives and a motivation to shift over to other constructs from this straightforward way of addressing data.
Namespaces became practical for me to introduce when I discovered that I could use 'our' declarations in a single file. That allowed me to move code to other namespaces while still accessing variables in the root namespace.
Although I want to refactor my code to be more reliable and easier to maintain, any steps will need to be sufficiently incremental. Over time I've found attempts at search-and-replace on variable names to be suprisingly error prone.