Style guide & best practices for ActionScript 3 (AS3)

Adobe Flash Best Practices and ActionScript 3 Style Guide.

“Code that only you can understand does not make you an advanced coder." - Some Smart Guy

Goals

When you look at a variable, class or function name, the way that the code is written should clearly denote to you what it is, where it is located, how it’s declared and something about what it does. Our goal is to name constructs in such a way that all these things are instantly apparent. We not only are looking at readable code but efficient and secure code.

Secondly we are looking at good asset management and FLA structure to improve the organization of the development pipeline.

Avoid Dogma

Remember, that these syntax recommendations are just guidelines. There may be a few times that the naming scheme makes coding more difficult or you have a strong reason for making an exception. In these instances you may break from the standard. However, it is a good idea to learn to be consistent so that conforming to the style becomes automatic.

Folder structure

There are a few folders that should be used as a standard when creating projects.

Classes

All action script 3.0, classes will be stored in this folder.

Fonts

All fonts should be saved in a fonts directory. Sometimes you will use a font then break apart the text field to turn it into a shape for a shape tween or another reason. It is suggested that when you do this you note the font name that you used in the layer name where the text is first appears, so that if later the text needs to be manipulated you will remember what font was used. This is also useful when recycling content years later when a new developer needs to customize the text for a new project and doesn’t have the font installed on his machine.

Attention: When using static or dynamic text, the operating system draws the device fonts, which are therefore unaffected by the quality property and can lead to small point differences. The fonts used should be compatible with both the mac and PC. This means tested on both systems. Don’t assume that just because most TrueType and OpenType fonts work most of the time on both systems that you’re in the clear. When a font that only works on one system is necessary then break apart the text. This is of course only necessary if your development team is using multiple OS(s).

Source images

All original JPG, PNG, GIF, ect. images imported to flash should exist in some external folder and be stored there in the project so that if we want to edit that image at a later date, we can just update the asset in the library rather than re-importing the changes as a new asset. (a good practice can be to store all source images in a standard directory structure at the root, like C:/sourceImages/yourName/ this way it will update on any machine if they have your source files and you will avoid naming conflicts.) If you are using a central asset storage server then you will want to beable to map the drive under a defined drive letter that is the same for all developers and import images from there. Even though the image paths will not work cross mac and pc, if one of your team mates needs to reimport an image this will make it much easier to do so.

Primary Naming Guidelines

When writting code native ActionScript is our guide. If classes are always capitalized then your classes will always be capitalized, if they use camel case you use camel case (more on camel case below), etc. Most importantly, an application's naming scheme must be consistent and names should be chosen for readability. This means that names should be understandable words or phrases. The primary function or purpose of any entity should be obvious from its name. The name should not imply that it does any more than it actually does.

Since ActionScript is a dynamically typed language (objects, arrays, XML, dynamic classes), the name should also contain a suffix that defines the type of object being referred to by the name. In general, "noun-verb" and "adjective-noun" phrases are the most natural choice for names. For example:

  • Class objects (first letter always capitalized) ScrollBar
  • Object Contructor actionscript 3.0 (always put classes in folder named classes, this way a declaration will always be obvious to what it is. The first letter of the constructor is always capitalized. You will see this syntax in native flash constructor objects like new Array() ) – var ThingsList = new ExtendedArray();
  • Variable names – waterSpeed (notice first letter of a variable name or function name is lower case, then between each word is defined by using an upper case letter, this is called camel case, and is the standard in ActionScript )
  • Variable names – soundVolume
  • Frame labels – -hello-world (no spaces or underscores. This helps the user know what kind of data we are dealing with in cases where it’s not obvious. Ex: someLoc_str = “-say-hello"; because it starts with a dash we know it’s a frame label right away, or some kind of prefix can be used for example "label-hello-world", "frame-hellow-world", etc.You choose it, just be consistent. I personally like the dash "-" because it is short )
  • ActionScript 2.0 coders should notice the difference between classes and data types. int, unint, void, ect… all start with lower case because it’s a single native data type, rather than a native data type the represents some sort of collection like MovieClip, Array and Classes.
  • Avoid using reserved words or language constructs as variable names in external data files, because doing so makes reading and debugging your code more difficult, especially when custom functions are highlighted as native to flash in your code editor.

Classes and object constructors, should be capitalized.

Function names and variables should begin with a lower case letter.

Functions should always use verbs, nouns are objects.

When creating handlers or call backs, choose the suffix handler, proxy, or callback and always be at the back of the function name. ex: userDataHandler();

Handlers or callbacks make code very difficult to debug through just reading the code. It is strongly advised that you avoid using callbacks whenever possible except in the cases where the function call is asynchronous.

When creating listeners, the word listener should always be somewhere in the function name. ex: userDataListener ();

In addition, words that are used by ActionScript should never be used as names. Also avoid using variable names of common programming constructs, even if the Flash Player does not currently support those constructs. This helps to ensure that future versions of the player will not conflict with the application. For example, do not do the following:

  • var = “foo";
  • MovieClip = “myMovieClip";
  • switch = “on";
  • case = false;
  • abstract = “bar";
  • extends = true;
  • implements = 5;

Since ActionScript is ECMAScript compliant, application authors can refer to current and future ECMA specification to view a list of reserved words.
Flash enforces the use of constant variables, authors should use a naming scheme that indicates the intent of variables. Constant names should be all upper case and separated with underscores for readability. For example:

  • const BASEURL = http://www.foo.com; //constant
  • const MAX_COUNT_LIMIT = 10; //constant

Classes

Distinguishing static variables from instance variables: From within a class that defines the static variable you should always reference them using the class name so that it is understood that this modification applies to all classes not just that instance. This also prevents static variables from being over written by local vars that may be declared in the local scope of a function. When a variable is not scoped flash first looks to see if that var exists locally if it doesn’t then it looks up the function call stack and then onto the object stack thus if you create a “shadow var" in a function with the same name as the static variable you will need the class name to distinguish the local from the static. Here is an example of how you should access static variables (the same convention should be used when using static functions):

//

package {

internal class TheObject {

private static var identifier:String = “your mom";

public function changeValue(){

TheObject.identifier = “his mom";

}

}

}

//

Naming for fast auto completion
Most of the new AS3 IDEs use autocomplete. Since most objects are strongly typed, the IDE knows when you type some class name what its resulting members will be. In order to maximize how fast you type code you should not name things in the following way:

//NOT THIS WAY:
class TheObject {
public static var settingsStartUp:String;
public static var settingsShutDown:String;
}

The reason for this is when you type TheObject it will attempt to guess what you are going to type next and when you type TheObject.se it will not know which variable to use. You will have to type TheObject.settingsS before it can correctly guess which one you intend to use. Instead you should use the category 'settings' at the end of the variable name in the following way:

//CORRECT WAY:
class TheObject {
public static var startUpSettings:String;
public static var shutDownSettings:String;
}

We generally think hierarchically and at times this may cause problems in cases where we have categories and subcategories or objects and properties. For instance you might have birdNumber and birdType it would be natural to name the variable in this way because this is how we speak and in most cases we want to follow the logic of coding in a way that is most intuitive, but in this case efficiency trumps intuitiveness. So just remember when you run into a category and have subcategories to swap the naming to typeBird and numberBird. If that does not meet your fancy try typeOfBird and numberOfBirds it does not matter that one ends inconsistent with the other in an 's' because you will never type past the first few characters if you are using strongly typed variables and autocomplete. If you name this way you can use long descriptive variable names at little cost to typing speed.


Code hints
(Code hint suffixes are only provided for historical reasons, in AS3 avoid using underscored suffixes)
The Flash ActionScript editor in old versions to cs4 has built-in code completion support based on code suffixes. In order to take advantage of this, without using strict data typing, variables must be named in a specific format. The flex perspective/IDE will auto detect your object type so in this case suffixing would be unecessary (See bellow for helpful suffixes under flex). The default format is to suffix the variable name with a string that indicates the variable type. Below is a table of supported suffix strings. The next two tables should be strictly adhered to for code readability. Not all data objects are listed here follow the example code in the Adobe Flash ActionScript documentation to find out what the standard suffix strings for code hinting is for each object. Though with flash 9 code hints is being replaced by strict data typing it will not auto detect the types you use that are passed from function parameters so it is best to continue with the code hints. If you are using flex builder/flash builder and you are exporting your SWCs correctly you do not need to follow this check out helpful suffixes under the flex IDE instead.

The following table lists the suffixes required for support of automatic code hinting:

Object type

Variable suffix

Array

_array

Button

_btn

Camera

_cam

Color

_color

ContextMenu

_cm

ContextMenuItem

_cmi

Date

_date

Error

_err

LoadVars

_lv

LocalConnection

_lc

Microphone

_mic

MovieClip

_mc

MovieClipLoader

_mcl

PrintJob

_pj

NetConnection

_nc

NetStream

_ns

SharedObject

_so

Sound

_sound

String

_str

TextField

_txt

TextFormat

_fmt

Video

_video

XML

_xml

XMLNode

_xmlnode

XMLSocket

_xmlsocket

For information on using code hints when they appear, see Using code hints.

The following suffix strings are not supported in flash’s code editor but we feel are necessary for consistency since these are commonly used in different publications.

Component Parameter

_param

myParameter_param

Component

_cmp

myComponent_cmp

Object

_obj

myObject_obj

Boolean

_bl

isOpen_bl see more for Booleans below

Scalars, custom classes and dynamic variables (except for certain cases listed under naming for flex) don’t need suffixes. For naming custom classes a suffix isn’t necessary but sometimes an indicator of that objects class can be incorporated into the name for clairity if the class name does a good job of explaining what the object does. For example:

myFLVPlayer = new Player();

Helpful suffixes used with the Flex Builder/Flash Builder IDE.

Mc or DisplayListMc: Since using suffixes is really a Flash IDE practice, Movie clips which show up on stage should still always be suffixed with mc. No _mc because when coding in flex camel case is the standard practice. This allows the programmer to clearly spot objects that are assumed to exist on the stage. It is very confusing when you see a MovieClip being accessed but you don't see its decairation anywhere. This practice saves the programmer time by allowing him/her to see that the MovieClip is being declaired on the stage just by looking at it. You can choose the suffix I don't like DisplayListMc because it is verbose and makes for a lot of typing. Feel free to invent your own but make sure that you are in agreement with everyone working on your code. Mc is very common so I suggest just sticking to that standard. Ex: playersCarGraphicMc

Obj: Dynamic objects should have obj some where in there name so that it is easy to find runtime errors. The use of the Object dynamic class creates slow running and hard to debug code. When you can, use a non dynamic class instead. Ex: mysteryBoxObj

Txt: Text that is found on stage should be suffixed with Txt. This is of course in line with the idea with Mc. Ex: scoreTxt

Btn: Buttons that are found on stage should be suffixed with Btn. This is of course in line with the idea with Mc. Ex: playNowBtn

When you are not sure where a symbol is located, this will help you identify that it is a graphical asset that lives on the timeline. Xml objects should always have the text xml some where inside it. testXML. Arrays should always be named as somethingArray, somethingList or more subtly be plural "things". I prefere using List and Array because like the Obj suffix it allows me to identify dynamic code. With ActionScript 10 or later you should avoid arrays and use Vector.

Passing by reference.

It is discouraged to reference members of another class from inside another. Clear APIs should be defined to pass information back and forth, or a clear event architecture should be established. But when you are in a rush there is nothing like passing a reference to an object into another object, and there is nothing that provokes confusion at a later date. To minimize confusion always finish your variables with Ref example: objRef. Make sure that when you pass the reference to the class it should always be done though an obvious and deliberate function. Always use registerMyClass(instanceOfMyClass) register is commonly used and you can easily spot it. Never pass references like this:

myNewClassInstance.objRef = otherClassInstance.

Further more if you store the reference passed through the function inside the class it is important to show that it is a reference. Make sure that you comment the member variable as to where the reference comes from and where it is passed in, along with suffixing the variable with Ref.

myNewClassInstance.registerOtherClass(otherClassInstance)

//here is what the function declaration looks like on myNewClassInstance

public function registerOtherClass(otherClass:OtherClass):void{

_otherClassRef = otherClass;

}

Here we are passing a class in by reference. If you have to pass something in by reference to get around the way you archetected your code it is much better to pass a class in so that where the reference comes from is clear. For example if you would like to pass in someArray you should pass in the class and then access the array off of the class.

The underscore at the front of variable names.

Naming variables starting with an underscore is a practice from ActionScript 2 that copies Macromedia’s usage to denote objects of the nature of _root or _global and properties of classes like _x. In ActionScript 3 these two usages of the front side underscore are out of date. You now only see the front side underscore for denoting private variables in a class. This can be seen commonly in various developers work, like joey lott’s and danny patterson’s book, actionscript 3 with design patterns.

Some programmers use the suffix as a dummy object for quick coding. Then you can just use the sufix for quick typing and still have access to code hinting. It is suggested that you simply use dummyStr or dumStr, dumMc, ect. This should be used only sparingly. Here is an example:

//this is bad, many programmers reserve this for private members of a class

_mc = this.aMovieClip_mc;

_mc.x = 1;

_mc.visible = true;

_mc = this.anotherMovieClip_mc;

_mc.x = 1;

_mc.visible = true;

//this is good

dumMc = this.aMovieClip_mc;

dumMc.x = 1;

dumMc.visible = true;

dumMc = this.anotherMovieClip_mc;

dumMc.x = 1;

dumMc.visible = true;

Now that _global and _root no longer exist and properties are handled differently (example x and y values no longer use underscores), you should consider some other possibilities discussed below.

Using the 'this', Class Files, and the front side underscore as prefixes.

Consider denoting class properties by attaching the “this" keyword (this.classProperty). This is much less contrived and uses actual functional constructs of the language. However, when you are referring to static variables you will have to use a simular but different technique. To access and identify static properties of the class you can reference them externally and internally with the class name. Ex: logger.loggingLevel = Logger.SERIOUS_ERRORS; This makes the coder instantly aware that SERIOUS_ERRORS is a static member of all logger instances since it’s clear that it’s attached to the Logger class. This is very compatible with using front side underscores to denote private. Logger._PRIVATE_ERROR, or this._privateMember as used internally to the class. It differentiates static properties, class instance properties and variables inside the function scope. Another way of denoting the scope of a variable is denoting inheritance with super.inheritedVal. These are just possibilities, most programmers stick to using front side underscores for private members and choose to leave the scope ambiguous.

Naming Boolean Variables

Start Boolean variables with the word "is" when ever you can (because a Boolean value either "is" or "is not" because of its nature). Therefore, you might use the following for whether a baby is a girl or not (which is a Boolean value).


isGirl = true;

Avoid naming your boolean variables things like isNotAvailable and use !isAvailable instead. If you still don't like the way that reads use isUnavailable, but stay clear of using the word "not" in your variable name. When you find your self wanting to use the prefix isNot try to think of what the opposite of the next word is and then drop the "not." Other examples might be isHidden instead of isNotVisible or isClosed instead of isNotOpen. This avoids confusion when you want to use something like !isNotVisible which translates to "not is not visible." When you read this in your head it can become confusing because it is a double negative. We don't use double negatives in writing and we shouldn't in coding either. This technique will help you avoid using this type of confusing logic which is more prone to errors.

Naming Interfaces

Starting interface names with an uppercase "I" helps you distinguish an interface from a class. The following interface name, IEmployeeRecords, uses an initial uppercase letter and concatenated words with mixed case, as follows:

interface IEmployeeRecords{}

Note: this is common and is strongly advised because it is how Adobe names interfaces, but it has often been criticized. Another standard to consider is Putting the ‘I’ at the end EmployeeRecordsI this way in your package the files group together by first letter. In the end what is important is to use whatever is already established among developers for consistency. Flash uses the convention of ‘I’ first (see IEventDispatcher), so it is best to stay consistent with the language that Flash/ActionScript already uses.

Naming Getters and Setters

When using the following function declarations in your classes.

public function get isLoggedInGet():Boolean{

return this.isLoggedIn;

}

public function set isLoggedInSet(isLgdIn:Boolean):Void{

this.isLoggedIn = isLgdIn;

}

The reason for this is that when you use these getters and setters it gets confusing for someone looking at your class from the exterior because you can’t tell that the value is being passed into a function and thus can be manipulated. For example:

public function get isLogIn():Boolean{

return this. isLoggedIn;

}

public function set isLogIn(isLgdIn:Boolean):Void{

isLgdIn = ! isLgdIn;

this. isLoggedIn = isLgdIn;

}

This is an extreme example where the programmer might be very confused why when he types someClass. isLogIn = true and then he traces someClass.isLogIn traces he gets false. If the functions are suffixed with get and set then the user knows that something may be happening inside the function call and that they are not looking at direct assignment. It is important to note that if you are trying to obfuscate what is happening inside your code than avoiding a naming convention is appropriate. Even in the debugger getters and setters look indistinguishable from variables. Mainly this functionality was developed for obfuscating functionality and for control of read/write access. If you have no need to control read write or to obfuscate your code then just use someClass.setIsLogin(true).

To avoid confusion, suffix all setters and getters with ‘set’ and ‘get’.

public function set isLogInSet

public function get isLogInGet

Variable names that use or are acronyms

There are two ways about it – populationInUSA or populationInUsa. Standardize based on your existing code or consensus among developers. I prefere populationInUSA because it is how Flash/ActionScript does arcronyms. The draw back to this is when you have things like fundingOfTheUSAEPA or USAFunding. In the case of USAFunding, the first letter is capitalized which means it's a class. This is a serious violation of style, so it would not be possible to put USA at the front. You'll have to find ways to not put it the begining of the variable name in order to continue to follow ActionScript's example. Also, USA runs into the "F" which is hard to read. In the case of fundingOfTheUSAEPA, this seems strange because we think of the United States of America (USA) as one thing and the Environmental Protection Agency (EPA) as another, yet they run together. Long acronyms are hard to read. So though Flash/ActionScript uses all uppercase for naming its acronyms, it has its limitations that you have to work around by being clever with langauge. This is the reason for which people tend to break from the way Flash is coded and stick with camel case for acronyms even though Adobe chooses all Caps for its acronyms.

Use semicolons at the end of lines of code

Many developers go back and forth between C, java, javaScript, PHP and ActionScript. Though you don’t need to use semicolons to end code lines in ActionScript or Java, using or not using them in a consistent manner will help you avoid errors in the other languages and will make your code more portable between ActionScript and whatever other language. It’s preferable to use semicolons since most languages either allow it or require it.

if (someObj.someVar) vs. if (someObj.someVar != null)

When you use if (someVar) to determine if a variable has been declared or defined, it looks like clean code because it is elegant and simple. This practice is discouraged for determining if a value has been defined because it can return false even in situations where the variable is defined. For example if someVar = 0 or someVar=false and even though it is defined the if clause will not run. If someVar is a property of someObj, then it is not subject to compile time checking. To maximize clairity use if (someObj.someVar != null) to determine if the variable has been defined or declared. Reserve the use of if (someObj.someVar) for when someVar is a boolean.

Declaring Variables

When you declare variables in a function, it is good form to put all the variables that are being used at the top of the function. This way the user can tell if a variable is local or if it lives somewhere else and quickly find all variables that are in the scope of that function. Some will have ‘If’ or ‘case’ statements that in the function that split functionality in which case it renders the declaration of certain variables useless. Declare the variables at the top of each code block as defined by the brackets. In this situation consider using a function call for each case.

Import statements

Imports that should be grouped by package, starting with flash libraries at the top of the list.

Commenting code

All significant blocks of code should contain headers, here is an example of a possible header: (classes, functions, components, …)

//*******************************

// TITLE: a quick 5-10 word description goes here

// DEVELOPER: this is useless if you are using a versioning system

// DESCRIPTION: a more in depth description on how it works, this should be brief, rely on

// comments through out the code for the details of how the code functions.

// FLASH VERSION: this is optional

//*******************************

Always comment code in an application. Comments are the author's opportunity to tell a story about what the code was written to do. Comments should document every decision that was made while building an application. At each point where a choice was made about how to code the application, place a comment describing that choice and why it was made. An important thing to keep in mind is that you do not want to reiterate your code in your comments. In other words don’t explain your syntax! Explain instead what you are trying to do.

When writing code that is a work-around for an issue with the application, be sure to add a comment that will make the issue clear to future developers who may be looking at the code. This will make it easier to address that specific problem the next time someone encounters it.

Here is an example of a simple comment for a variable:

var clicks = 0; // variable for number of button clicks

Block comments are useful when a comment contains a large amount of text:

/*

Initialize the clicks variable that keeps track

of the number of times the button has been clicked. Blah blah balah!!

*/

Some common methods for indicating important comments are:

// :TODO: topic

Example

/*

:TODO: msw 654321 : issues with displaying large set of data from the database. Consider breaking up the data into smaller chunks for each request.

*/

Indicates that there is more to do here.

// :BUG: [bugid] topic

Shows a known issue here. The comment should also explain the issue and optionally give a bug ID from your bug management system like bugzilla or others, if applicable.

// :KLUDGE:

Indicates that the following code is not elegant, a quick temporary fix or does not conform to best practices. This comment alerts others to provide suggestions about how to code it differently next time.

// :TRICKY:

Notifies developers that the subsequent code has a lot of interactions. Also advises developers that they should think twice before trying to modify it.

// :TEST:

Notifies developers that this was used for testing, if test stuff gets left in code it can help to know what is not essential and can be removed.

Commenting: variable names that are acronyms

Sometimes your variables will be to long and descriptive so you will have to inevitably use elusive variable names. Key variables should always be declared in a centralized place (like the top of a function) with an included comment that describes the variables function. This becomes particularly important when the variable is an acronym liketimeSlbl. Make sure variables like this have the acronym definition in a comment like.

// time since last byte loaded

var timeSlbl = 0;

Break Point Code

Break point code is where the debugger requires you to put in junk code inorder for the break point to catch. Randomly naming your variables creates clutter in your debugger variables window. If you name them consistantly it will be easier to browse variable lists with minimal disruption. Especially if there are a lot of these variables in the current scope, they will all be bunched together making it easy for the eye to dismiss them in one big block.

if (isDebugCondition){

var breakpoint1:uint = 0;

}

Swf file names

Finally, all SWF files should have names that are consistent in format so that when doing external loads, for example, you won’t have any doubt on the format of the name of a file. Like in the case of loadBar.swf vs. Load_Bar.swf it would be easy to forget which way the file name was formatted. Eliminating the doubt that requires you to go back and verify formatting is a good idea for increasing coding speed and accuracy. Have a naming convention and stick to it.

Strict Data Typing

Use strict data typing with your variables whenever possible because it helps you in the following ways:

* Adds code completion functionality, which speeds up coding.

* Generates errors in the Output panel so you don't have a silent failure when you compile your SWF file. These errors help you find and fix problems in your applications.

var params_lv:LoadVars = new LoadVars();

Error checking

Whenever an error is displayed by using trace or error reporting mechanism, make sure it is apparent where the error is occurring (in what movie and what class or function). One of the best ways to perform error handling in ActionScript is to use the try-catch-finally blocks that let you throw and catch custom errors. By creating custom error classes, you can reuse code throughout your application without having to rewrite error handling code. For more information on throwing custom errors, see Error in Flash Help or the Flash 8 LiveDocs (ActionScript 2.0 Language Reference > ActionScript Classes > Error). For more information on try-catch-finally blocks, see Try...Catch...Finally Statement in Flash Help or the Flash 9 LiveDocs Try..Catch..Finally Statement. If you are not throwing custom errors, but building code that recovers after ActionScript throws an error, It is not always a good idea to use try...catch blocks when you are doing debugging. While you have the application inside of your testing environment like flex/flash builder. You want to take the fail fast approach so that when the debugger detects the runtime error it stops on that line of code. Tracking back thrown errors to the line where they occured is a pain. When you send your site out live, try...catch blocks should be firmly in place with routines to report the error back to your server or recover from the error. These will keep people with the debugger version of the player from seeing your poor programming when trivial errors occur.

Library layout and Asset Management

The goal of standardizing the naming of symbols in the library is that different resources can be quickly located and the nature of the symbol will be apparent to the developer at first sight. Make MovieClip names clear and understandable. When possible relate the stage instant’s name to the library name (library : car, instance : car_mc). In some situations it’s just good to have everything in one large list so that you can jump to them in the library list alphabetically with shift-‘a’ (the first letter of the symbol). However it is advised to use folders in the following situations. Repetitive graphics should be put in folders similar to the names of their associated movie clips. For example I have imported a sequence of images for an animation footballplayer1,jpg – footballplayer200.jpg. these 200 images should be put into a folder called footballplayer jpgs and the movie that holds the animation should be called football player. Don’t bury your library assets by giving them meaningless repetitive prefixes like putting UI in front of everything or Nav. Ex: NavTop, NavBottom, NavSub1, NavEct ect. This is what folders are for put these under the folder navigation and name them top, bottom, sub1 Ect. If you keep your names unique you can jump to them with the shift button and locate them in the library much faster. Make good use of folders, but do not over use, you can just as easily over organize and bury assets in a maze of nested folders. It is preferable to avoid nesting more than one level deep.

If you build components, organize all custom components into the componentsSomeName folder along with their assets so that they can easily be transported and reused else where. This is particularly important if the component uses linked assets in the library that won’t get transferred by a simple copy and paste of the root of the component. Any time you are using linked library elements they should be packaged with their base movie and corresponding components.

When a MovieClip is no longer needed, make sure it is removed from the library. You can do this using the remove unused symbols in the library menu but make sure you unselect any linked library elements. Since they get called on stage with actionscript there is no way for the remove unused symbols to detect if they are used or not.

Shared libraries (version 6-9this function is buggy when developing multi-swf projects that load movies dynamically, it is advised not use shared libraries when you are externally loading multiple interdependent external SWFs. For this to work the root movie clip has to have the shared assets included in its library which eliminates any of the apparent size benefits of incremental preloading. It may work in current versions of the player but keep a lookout.) However it is useful if you want to have a set of external location where you change the shared library once and see your changes deployed across your other SWFs.

Timeline layout

Developers should avoid using the default layer names (Layer 1, Layer 2, etc.) as this can become confusing. Timeline layers should always be named intuitively. Layers should also be grouped together using folders, where it makes sense. For example, there could be a Script folder in each timeline if your timeline is already crowded with other layers of graphics. Within that folder there will be layers called Labels, Actions, Classes and Functions respectively. Attention to the order that your SWF layers are being loaded which is defined in the publish settings, this effects the functionality of where your functions are being loaded and being called.

It is also good practice to lock all of the layers that are not currently in use. This prevents accidental changes to the document.

ActionScript conventions for timeline coding.

Keep actions together

You should avoid coding in the time line whenever possible. All code should be placed in one location, unless the process of doing this further complicates your code. This is true of timeline coding try to keep as much code as you can in localized and organized spots. This makes the code easier to find and debug. One of the primary difficulties in debugging Flash movies is finding the code. If most of the code is placed in one frame, this problem is eliminated. Usually, the best place to put the code is on frame 1. This of course is only a problem with timeline coding.

When large amounts of code are located in the first frame, make sure to separate sections with comments to ensure readability, with layers and/or as follows:

/*** Button Function Section ***/

/*** Variable Constants ***/

One exception to the practice of placing all the code in frame 1 arises when movies will be preloaded. In an application with preloading movies, placing all the code in frame 1 may not be possible. However, authors should still strive to place all of their code in a centralized location.

For movies that have a preloader, start the actions in frame 2. Use two layers for actions-one layer for functions, and another layer for state dependent actions.

Remember that all functions and objects created in ActionScript live for the entire movie. And yet, movie clips are created and destroyed based on the timeline state. The timeline should reflect this relationship.

Versioning Control Systems and External ActionScript (.as) Files

By using external ActionScript files, developers can integrate the files with a version control system, such as CVS, Sub-Version or SourceSafe. Once again, when used correctly, this makes code more modular and easier to find. Just because you keep your code separate does not mean it’s easier to read. When dealing with document classes you need to make sure they are named in a way that associates the ActionScript file with the FLA. (Strictly adhere to the following convention)

Finding objects in the library.

You don’t need to give the full path to the movie name but the movie name should be a unique name in the library. You should prefix library class names that have no external as file with some sort of indicator so that it is known that the symbol is found in the FLA. For instance F for FLA or Lib for library. An example of this would be when I have created a symbol in the library called FBackground when I pull this symbol from the library in my .as file it is instantly obvious that the symbols implementation is in the FLAs library. If it’s placement in the FLA is at all ambiguous you should have a comment in your .as file at the top that informs the user of its particularities. For example:

//found in: someFile.fla : library item wheel, found on stage(timeline) under (/holder_mc/wheel_mc)

// lib item wheelBarrel, found on time line under (/holder2_mc/wheelBarrel_mc, /holder2_mc/wheelBarrel2_mc)

//found in: someOtherFileTo.fla : library item ect ect


Frames as application states

Developers often only use in-line code in the frame action to define the state of the application. This practice is discouraged.

For proper code organization, use key frames to delineate application states. Place any actions necessary for a particular state into a function and then call the function as the only action done in that keyframe.

To further organize the application, create two layers for code in the movie. The majority of code is located in one layer that exists for the entire length of the movie. The other layer includes actions necessary on the key frames to delineate the state changes of the application. The only code on each of these key frames should be a function call for that particular application state. It is also possible to use movie clips attached at runtime with the attachMovie() action to represent different states (such as dialog boxes).

Optimizing Your Code

Remember the following guidelines when you optimize your code:

1.) Avoid calling a function multiple times from within a loop. It is better to include the contents of a small function inside the loop. Function calls are the most time intensive single operation. If the code is only used once then use in-line code. However this is not acceptable if it renders the code difficult to read where it is crucial that the code is readable.

* Use native functions when possible. Native functions are faster than user-defined functions.

2.) Don't overuse the Object type. Data-type annotations should be precise, because it improves performance. Use the Object type only when there is no reasonable alternative.

3.) Avoid using the dynamicObject[“aMember"] or array access operator to access the same piece of data over and over. Often, setting the local reference once is preferable and more efficient. aMemberRef = dynamicObject[“aMember"]; then you can call your access over and over on aMemberRef.

4.) Assign the Array.length to a variable before a loop to use as its condition, rather than using myArr.length itself.

5.) Focus on optimizing loops, and any repeating actions. Flash Player spends a lot of time processing loops (such as those that use the setInterval() function or onEnterFrameevent). Don’t let onEnterFrames run needlessly.

6.) Type cast your variables and functions.

Security

Always protect your SWFs from imports with a good password.

Caution: Never store any information or code in a SWF file that you don't want users to see. It is easy to disassemble SWF files and view their contents using third-party software. With web applications you can put a lot of your functions in scripts on the server and just make calls to them from flash making each function a black box.

Use the final keyword for class methods: Making a class or a method final prevents other programmers from extending the class or overriding the method for the purpose of examining the class’s internal structure. Such prevention is considered one of the ways to safeguard an application from being maliciously exploited. Keep in mind that on the other hand, others argue that final methods and classes contradict the general object-oriented principle of polymorphism, wherein an instance of subclass can be used anywhere an instance of its super class is expected.

Perhaps the most obvious security measure for your application to add is a cross-domain policy, which prevents unauthorized domains from accessing your assets.

For more info: http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps_print.html

Conclusion
Based on Nicholas G. Dunbar’s years of development experience in ActionScript as applied to the following works:

comments powered by Disqus