Tuesday, April 13, 2010

Using Globals - I Didn't Think It Could Happen To Me

Well it can. And it did. I used globals. And it blew up in my face.

I'm writing a web application with a lot of Javascript. Javascript is a bit of a strange animal because of how "library" files are included individually, and the order in which you include them can affect the scope of some variables (by scope, I of course mean where the variables can/can't be seen and used). Please correct me if I'm wrong.

So I needed a variable that would be initialized when the web application loads, and I need to use this variable in many many areas throughout the code. Making it global was the easy, easy solution. The only alternative I saw? Passing this variable in and out of many functions, which I foresaw creating spaghetti-like scope issues and extra time debugging. So, globals it was.

And maybe when it's a small application, which this is moderately small (but growing all the time), you can get away with one or more globals. Or if you're the only developer, and you've designed all the code - you know how/when/where (you hope) the variables get used, so you can throw in a global or two.

But for this particular task, I was farming out some of the development to two other developers, who due to their location, I have limited communication with. And here's where it happens: one of the other developers used a function I wrote in an unexpected way. A smart way - good for him for not re-writing a bunch of code to achieve something current code already did, however "hacky" it was (and I think we must accept some level of hackiness with applications. You can't redesign every time there's a quirk). AND, the function which was used unexpectedly, was also a function that modified the value of the global.

BUSTED.

I began seeing some strange errors and realized that I was over-writing some of the data I was saving to the database. I finally traced it back to this problem, and realized I had just committed one of the major programming sins. Well boo me, but globals still seemed like a better idea than passing the variable around to tons of functions. What do you think? (No seriously, what do you think? I write these posts because I'm interested in takes from other developers. I might learn something!!).

No comments:

Post a Comment