Flash Authoring Quality Assurance Engineer

Writing clean codeâ€¦. (No globals and no _root)

Hi gang,

While I know it can be difficult; I have always found it best to recommend that programs can and should be written without the use of global variables and without targeting _root. While both techniques are valid and do have their place, the convenience of using them tends to encourage programmers not to place their code in a centralized location or to be smart about their use of memory.

In the case of globals, developers get the convenience of not having to remember the path to their objects or variables and thus can use them freely. This can make it very difficult to debug your code when something goes wrong. Several functions reading and writing from a global variable can often lead to an unexpected overwrites of data in your variable and it can be a nightmare trying to track down exactly the sequence of events that cause the problem.

Furthermore I canâ€™t begin to tell you the number of support cases we get where a user has of created fairly large data structure stored in global objects or arrays not realizing that to make anything global is to disable the automatic garbage collection (of that object or variable) the player does to keep memory being used efficiently. After a few seconds you can literally see the usage of RAM building on the system followed by a dramatic performance drop because the explicit â€œdeleteâ€? statement was not ever used to free up the memory of the objects that were no longer needed.

Use of _root tends to encourage programmers to scatter code in various child movie clips and on handler events. This can make tracking down a problem just as difficult as when you use globals. Also, at some point there tends to be some reason that SWF must be loaded into another. Storing data in _root means you increase the chance of overwriting data stored in the root movie or creating variables in the root that do not get removed when the child SWF has been unloaded or replaced. This leads to a reduction in the available memory in much the same way overuse of global variables does.

So what should you do? Well just avoid the use of global variables and _root. You can always store you data in a specific movie clips (or on the frames of the main timeline) and you can always use relative paths to target those movie clips or whichever timeline contains the code you need to target. Forcing yourself to follow these rules will help you get better and understanding scope and will encourage you to think about structuring your application before you write it. This will help you to keep your code a bit more organized, and eventually will lead to less bugs. Over all it will make it much easer to troubleshoot bugs when you get them.