devxlogo

Organize Your ActionScript:Six Strategies for Healthier Flash Code

Organize Your ActionScript:Six Strategies for Healthier Flash Code

e are witnessing increasingly ambitious projects software in Flash. A quick look through the Macromedia Showcase for Flash proves that Flash is no longer just for animations or for dazzling wandering Web visitors. Rather, Flash has matured and is now being used for a host of front-end tasks, such as chat and IM clients, interactive training applications, wireless and PDA applications, and interfaces to commercial applications. Where HTML falters, Flash takes over.

Along with Flash’s newfound importance as a development technology comes a responsibility to maintain Flash-based applications, some which may be mission-critical. Unfortunately, it is considerably more difficult to write clean and maintainable ActionScript than it is to write code in other programming languages. ActionScript quickly turns into spaghetti code that only the original author understands; therefore, trying to understand a complex Flash movie written by another programmer can be a daunting task. Why does ActionScript get out of hand so quickly? Here are some of the most important reasons:

  • Code gets “lost.” ActionScript can be attached to so many different places in Flash movies (buttons, frames, movie clips) that it often gets lost in some dark, forgotten corner of the movie.
  • Editing tools are poor. Flash’s built-in ActionScript editor is poor. It has no syntax highlighting, poor searching features, and a single window for code editing, among other things. As a result, ActionScript code is more difficult to read, follow, and?most importantly?refactor.
  • Object-oriented programming is not widely used. OO is not yet a common standard for Flash authoring. As a result, longer ActionScripts tend to become a maze of functions where the main logic is difficult to follow.
  • ActionScript Movie Clips are new to most programmers. Movie Clips are analogous to variables and objects from other programming languages, but not exactly like them. Most developers aren’t sure how to handle them, and so tend to do so inconsistently.

Six Simple Strategies
In the rest of this article, I’ll present six simple strategies that can help you write readable and maintainable ActionScript that will keep future programmers from groaning over changes or new feature requests to the Flash applications you’re building today.

Strategies 1-3
1. Place all code in the main timeline (timeline for the _root clip)
This is the single most helpful way to help the programmer who will follow in your footsteps. Rather than attaching huge handler scripts directly to buttons and clips, have a single line of code in the event handlers call a function in the main timeline.

   // Good example: Use code like this.   on (press) {      _root.doSomeAction();   }      // Bad example: Avoid code like this.   on (press) {      [insert lots of code here that forces the developer to move back and forth between this clip and the main script]   }

To make the event model of your Flash movie even more apparent, attach the handlers for various events in the main timeline as well. That is, to attach a handler to a button, do the following:

      function doSomething () {         //event code here      }         myButton.onpress = doSomething;

The advantage of using this technique is that it makes it obvious to later programmers that an event has been attached to a button, and the programmer no longer has to search through all the buttons to see what handlers are called.

There’s no good approach for refactoring existing code using the tools provided by the Movie Explorer…unless all your code is in one place.

Some may argue that it’s OK to attach code to buttons and movie clips directly, after all, isn’t that why the Flash developers provided the Movie Explorer window? In my opinion, however, the Movie Explorer is more of an indication of the problem than a solution to it. There’s no good approach for refactoring existing code using the tools provided by the Movie Explorer. For example, try to search-and-replace all occurrences of a function or movie clip name. The Movie Explorer can’t do that unless all your code is in one place.

2. Make complex movies one frame in length.
The purpose of using ActionScript is to manipulate movie elements programmatically. The traditional way of doing this in Flash is to use multiple frames and tweening or other methods for moving these elements on a frame-by-frame basis. However, this practice causes problems with ActionScript-controlled movies. For example, scripts frequently “lose” references to Movie Clips because they aren’t in the “current” frame of the movie.

It’s tempting to use frames to reflect the state of an application (for example, after the user logs in, go to frame 2), but that can be a dangerous strategy. Movie Clips from other frames will be unavailable in frame 2, and if you try to reference them, you’ll get errors. Unless you have a lot to gain from using frames in this fashion, it’s best to leave all control to ActionScript. If you want to change the interface, hide the Movie Clip holding the current interface and make the new one visible using script. Turn interface elements on and off.

A bit of esoterica here?you can reference ActionScript functions and variables across frames, but you can’t reference Movie Clips across frames. Worse, if you try to store a reference to a Movie Clip in a variable and reference it in another frame, you’ll find that the reference is no longer valid! More on this later

3. Handle animations as separate Movie Clips.
This is closely related to strategy #2; if you need to use animations, place the animations in separate movie clips, and then place these clips in the main timeline. That way, the main timeline will still only be one frame in length, while embedded animations can have multiple frames. Having “child” movie clips contain multiple frames is usually fine, and won’t cause problems with references to variables and Movie Clips.

Strategies 4-6
4. Use ActionScript/JavaScript objects.
Object-oriented code is much easier to read (and therefore maintain) than non-OO code, especially as code gets longer. A few OO techniques can go a long way towards clarifying the design underlying your ActionScript code, thereby making it more readable and maintainable. Those unfamiliar with OO design and programming need not fear?some OO techniques are rather simple. As a starter step, use objects to group together related groups of data.

   // Document object   function Document (title,subject) {      this._title = title;         this._ subject = subject;   }      Document.prototype.getTitle = function() {    return this._title;   }   Document.prototype.setTitle = function(val) {    this._title = val;   }

Dealing with a Document object instead of an array of document data will improve the readability of your code.

Given the scant attention to Flash’s object-oriented features in the Flash documentation itself, it is not surprising that object-oriented ActionScript is not a standard. Luckily, there are many articles and tutorials available on OO techniques, and some are ActionScript-specific as well. See the Related Resources section in the left column for more information.

5. Adopt some simple strategies for working with Movie Clips.
First, use the attachMovie method with linkage IDs and avoid using duplicateMovieClip. Using the latter can clutter your workspace with Movie Clips waiting to be duplicated.

Another good technique is to save references to important Movie Clips in ActionScript variables. This allows you to reference them later without having to use long Movie Clip “path-style” references that can easily break. For example, suppose you have a Flash movie about the circus, and you want to place another clown on the interface. If the Movie Clip has the linkage id “clown”, you would do this:

   _root.workarea.mymovieclip.attachMovie("clown1",      "clown",depth);

Now you can get a reference to that clip.

   clownClip = mymovieclip ["clown1"];

You can use the clownClip reference later, for example:

   clownClip._xscale = 125;

The reference variable is better than using a fragile hard-coded reference as shown below, which will break if you modify the name of workarea or mymovieclip or otherwise rearrange their hierarchy.

   _root.workarea.mymovieclip.clown1._xscale = 125;

Often you will want to save references to clips which are duplicated multiple times in arrays, as in:

   _root.workarea.mymovieclip.attachMovie("clown1",      "clown",depth);   var clownClip = mymovieclip ["clown1"];      clownArray.push(clownClip);   

Perhaps even better, save the reference in the Clown object instead.

      [in Clown object definition]   Clown.prototype.getMovieClip = function() {    return this._movieClip;   }   Clown.prototype.setMovieClip = function(val) {    this._movieClip = val;   }            [later, after clownClip created]      clown.setClownClip(clownClip);

By storing references in variables and objects, you no longer have to worry about where they reside in the hierarchy of Movie Clips.

Note that the preceding code uses the ActionScript keyword var to show that this is a local variable, not a global one. You should avoid globals as much as possible?they’re easy to modify accidentally. I often like to prefix movie clip references with “mc” (as in mcClown) or suffix them with “clip” (as in clownClip) to remind myself and others that the reference is a Movie Clip reference rather than a variable or other object reference.

6. Use Java/JavaScript coding conventions, or strive for another clean, clear style.
Common conventions include camel casing (i.e. camelCasing) variables, standardized indenting, avoiding if() statements without braces, etc. Standardizing programmers’ coding styles is important; most of the cost of software is in maintenance, not in development (maintenance accounts for 80% of software costs according to the Code Conventions for the Java Programming Language), and often software is not maintained by the original programmer. Given these two facts, we developers need to do everything we can to improve the readability and comprehensibility of our code.

Because Flash’s built-in ActionScript editor is “no-frills,” clean code is especially important. The Flash ActionScript Editor lacks advanced analysis and display features common to other code editors. The missing features include syntax highlighting, code-skeleton displays (also called code folding or collapsible code sections), auto-formatting, and refactoring tools. Remember, the programmer who follows in your footsteps will have only the text formatting that you leave behind as a guide. Make your code attractive and consistent by using standardized coding conventions. See the links in the Related References section for links to a couple of style guidelines that describe coding conventions useful for ActionScript.

Code for the Future
Thousand-line or larger Flash movies and months of development rather than days or hours used to be the exception in Flash development; now they’re commonplace. The last Flash application I wrote contained 850 lines of ActionScript code and took two months to write. During development the client provided regular feedback on features and usability, and I expect another call any day now, requesting further changes to that application.

In the context of larger projects like these, coding with code maintenance in mind is no longer optional. Organizing ActionScript code protects your work. The sanity you save somewhere down the road may be your own!

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist