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!

devx-admin

devx-admin

Share the Post:
Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security.

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists

AI Tool

Unleashing AI Power with Microsoft 365 Copilot

Microsoft has recently unveiled the initial list of Australian clients who will benefit from Microsoft 365 (M365) Copilot through the exclusive invitation-only global Early Access Program. Prominent organizations participating in

Microsoft Egnyte Collaboration

Microsoft and Egnyte Collaboration

Microsoft has revealed a collaboration with Egnyte, a prominent platform for content cooperation and governance, with the goal of improving real-time collaboration features within Microsoft 365 and Microsoft Teams. This

Best Laptops

Top Programming Laptops of 2023

In 2023, many developers prioritize finding the best laptop for programming, whether at home, in the workplace, or on the go. A high-performing, portable, and user-friendly laptop could significantly influence

Renaissance Gaming Magic

AI Unleashes A Gaming Renaissance

In recent times, artificial intelligence has achieved remarkable progress, with resources like ChatGPT becoming more sophisticated and readily available. Pietro Schirano, the design lead at Brex, has explored the capabilities

New Apple Watch

The New Apple Watch Ultra 2 is Awesome

Apple is making waves in the smartwatch market with the introduction of the highly anticipated Apple Watch Ultra 2. This revolutionary device promises exceptional performance, robust design, and a myriad

Truth Unveiling

Unveiling Truths in Bowen’s SMR Controversy

Tony Wood from the Grattan Institute has voiced his concerns over Climate and Energy Minister Chris Bowen’s critique of the Coalition’s support for small modular nuclear reactors (SMRs). Wood points

Avoiding Crisis

Racing to Defy Looming Financial Crisis

Chinese property developer Country Garden is facing a liquidity challenge as it approaches a deadline to pay $15 million in interest associated with an offshore bond. With a 30-day grace

Open-Source Development

Open-Source Software Development is King

The increasingly digital world has led to the emergence of open-source software as a critical factor in modern software development, with more than 70% of the infrastructure, products, and services

Home Savings

Sensational Savings on Smart Home Security

For a limited time only, Amazon is offering massive discounts on a variety of intelligent home devices, including products from its Ring security range. Running until October 2 or while

Apple Unleashed

A Deep Dive into the iPhone 15 Pro Max

Apple recently unveiled its groundbreaking iPhone 15 Pro and iPhone 15 Pro Max models, featuring a revolutionary design, extraordinary display technology, and unrivaled performance. These new models are the first