2008-03-20

5 Things: Globals

Lions and tigers and globals! Oh my! For practically every programmer, the later is the most terrifying, especially since we will likely never encounter the former in the wild. The reality is that we've all encountered them, most of us have used them at some point (it seemed like a good idea at the time), and we've double cursed their existance later on.

I cannot stress strongly enough that global variables are made of evil and hate! By definition globals invariably result in [side effects]. This was painfully illustrated recently when a minor external change had a major impact on a, seemingly, unrelated system. As a result some reporting was skewed, though not catostrophically, with data that was not quite what was expected. A flurry of emails and a day's worth of investigation later the two lines (one really) that caused the problem were discovered (by yours truely). The fundamental culprit?

$id = $author->prefix;

That's right. As it turns out, for legacy support reasons, $id is a global variable that comes from... somewhere else. We've got good people and it naturally seemed safe to use $id (I'd have thought so), and it should have been.

In this case the impact was serious but not disastrous, in others it could have been. Regardless it clearly illustrates why you should not use globals! If there is some compelling reason, like legacy code or held-at-gun-point, it's critical to be aware of what variables are global. To that end a simple [naming convention] could have easily prevented this: $g_id for example. In a perfect world we don't use globals, we use scoped variables and [namespaces]. They are dirty, we ostracize them and relegate them to old Basic programs where they can:

goto 666

No comments:

Post a Comment