Wednesday, September 06, 2006

Globals in Director, Flash, and Perl... Oh my!

Globals can be the bane of the programmer who needs to maintain another programmer's code (and sometimes even his own). When you use a global variable in a function, you've added another entrance and exit point for data into the function. When you change the state of a global, you are changing the state of the application. It makes debugging problems more difficult.

For years I worked with Director. In Director's language, Lingo, you can use global variables. I avoided using them, but occassionaly they were useful in transfering data from one movie to the next. In order to better handle the problem of maintaining code with globals, I took a page out of the OOP handbook and created getter and setter functions. This way I had an easy way to intercept the change in value of a global or even just determine when a particular global is being read. In fact sometimes, the globals would add up to the suggestion of the necessity of another parent script.

As I work with Flash and it's language, ActionScript, I find myself using a similar strategy. Flash also supports global variables and they are even more convenient to use than in Director (where you had to declare their usage). So I've created getter/setter functions for ActionScript (see below). A difference with ActionScript is you do not need to declare a global before using it. This necessitates more discipline. I try to give globals initial values in the same script as the getter/setter functions. The GetGlobal function will send a message to the Output window if you set an undefined variable. This helps since you can easily mistype a variable name and ActionScript will simply assign it without complaining. You can see in the SetGlobal function I commented out the line to trace what is being assigned. It is a useful place to test for a particular variable name and value if you are debugging.



As I learn Perl, I read that Perl's variable's are global by default unless you declare them with the "my" keyword. If that is the case, it will take even more discipline to write Perl programs in a structured (or object-oriented) manner.