Saturday, October 01, 2005

Variably Global?

A good friend of mine and me were discussing global variables. One of our older projects has quite a lot of them and, with various compilers different scoping rules, there has been some strange effects between accidental duplicates. Nothing serious and the original problems were a mixture of a lack of conformity and lack of warnings - both from an old compiler.

This got us talking about global variables in general. I was saying that I thought globals are generally a bad idea and he was saying that they don't pose any more risk than some other language features.

I know that I don't think this about global functions and I wonder why? Perhaps it's because that part of easily traceable flow of execution? Theoretically namespace conflicts can be a problem with global anything if you are not careful - not that I've had the problem (and C++ namespaces can provide the solution if necessary).

I always take care to make my module level variables and functions local to that file (static since this project is mostly C). Certainly I suspect some 'OO-purists' might say that they think global functions are a bad idea and so are module level anything - and everything should a method/member functions of a class and variables should be class instance variables only.

So I am still left wondering why they are so bad according to the warnings in literature and on the web.

Some of the warnings talk about unexpected alteration which I guess might be a problem in a very big program or in a program where the usage of the variable is not well understood coupled with a bad name or something. But might this failure mode not happen in another way equally as often? Not understanding the modes of a program is certainly not localised to global variables. Someone must have statistics for different sizes of program I guess - but they would need to compare then to the same failures using other methods?

I guess the unexpected mutual dependancy problems really depend on how you use global variables. It is not like the goto problem where there is a entirely better way that's as simple to use* since, for instance, you can get a mental parameter argument overload when too many parameters are passed. Global things are really useful sometimes - to the extent that OO-purists have duplicated a complicated version called a "singleton". Tell me that's not effectively a global class instance!

*I think gotos have nearly entirely died out from programs not because of the spaghetti code that some people would generate but because goto got replaced because more readible, more usable flow control methods could be used easily to express the same thing.

Oh well, back to my canned variable font code.


Post a Comment

<< Home

Newer›  ‹Older