best practices coding conventions as v1.1

Upload: -

Post on 06-Apr-2018

244 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    1/32

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    2/32

    Release Notes Private and confidential Page 2 of 32

    REVISION HISTORY

    Date Version Description Author

    15-Dec-05 0.1 Created Pradeep

    28-Jan-06 0.2 Reviewed and updated Shivani, Sajal

    05-Mar-06 0.3 Document updated based on the discussion during intial training

    program. Participants Neena, Taran, Shivani, Pushan, Brijesh, Arvind,

    Anish, Komal, Nitin, Dinesh, Sameer Gupta, Pulkit, Prasad, Shefali,

    Pradeep

    Shivani

    08-Mar-06 1.0 The document has been updated with the change in the variable

    naming convention; few corrections have been done to bring

    consistency in the coding style and an example of documentation

    commenting has been included.

    Pradeep

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    3/32

    Release Notes Private and confidential Page 3 of 32

    TABLE OF CONTENTS

    1 Objective 42 Introduction 53 Naming Conventions 63.1 General naming guidelines 63.2 Never use reserved words or language constructs 73.3 Naming variables 83.4 Naming constants 103.5 Naming functions and methods 113.6 Naming classes and objects 113.7 Naming packages 123.8 Naming interfaces 133.9 Naming custom components 134 Using comments in your code 144.1 Adding comments to classes 5 ActionScript coding conventions 5.1 Keep your ActionScript code in one place 175.2 Attaching code to objects 5.3 Handling scope 176 ActionScript and Flash Player optimization 266.1 Optimize your code 267 Formatting ActionScript syntax 277.1 General formatting guidelines 277.2 Writing conditional statements 287.3 Writing compound statements 297.4 Writing a for statement 307.5 Writing while and do..while statements 307.6 Writing return statements 307.7 Writing switch statements 317.8 Writing try..catch and try..catch..finally statements 317.9 Using listener syntax 32

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    4/32

    Release Notes Private and confidential Page 4 of 32

    1 ObjectiveThe developers (we) must write code and structure applications in a way that is

    intuitive and beneficial to themselves as well as to the other people who are

    working on the same/other project. This is particularly important in FLA files withlots of assets, or long code files. The objective of this document is to enforce and

    formalize the Flash development and coding process.

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    5/32

    Release Notes Private and confidential Page 5 of 32

    2 IntroductionThe guidelines in this document encourage consistency for people working in

    different projects or learning how to use Flash and write ActionScript code. It is

    expected from all of us to follow the topics as a guideline when we are workingwith Flash.

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    6/32

    Release Notes Private and confidential Page 6 of 32

    3 Naming ConventionsThe readability of your code is important for debugging, troubleshooting, and

    practicing general maintenance which amount to the 80% of the development

    time (sometimes even more). When you follow naming conventions, you increasereadability, which increases workflow and enables you to find and fix any errors inyour code.

    3.1 General naming guidelinesAll variables must have unique names. Names are case-sensitive in Flash

    Player 7 and later. Do not use the same name with a different case. Keep thefollowing guidelines in mind when you name items such as variables, files, and

    classes in Flash:

    Limit your use of abbreviations

    Use abbreviations consistently. An abbreviation must clearly stand for only onething. For example, the abbreviation "sec" might represent "section" and

    "second."

    Concatenate words to create namesUse mixed-cases (upper and lower case) when you concatenate words to

    distinguish between each word for readability. For example, select myPelican

    rather than mypelican.

    Name a file by describing the entity, process or activity typeEach file should contain only one class, which can be an entity class e.g. Student

    or a process e.g. AdmissionProcess. These files should be named with the class

    name e.g. Student.as or AdmissionProcess.as. The development approachshould always be Object Orient regardless you are working in AS 1.0 or AS 2.0.

    Separate AS files should be created for:1. Writing classes (file should be named after the class).2. Writing initialization code of the application (_level0 only) (file should be

    named initialize.as).

    3. Writing application configuration variables (file should be namedconfig.as). Another better approach can be to load configuration variables

    from an external XML file named config.xml. This allows for changing the

    application configuration without recompiling fla files.4. Writing reusable event handlers (file should be named logically with

    EventHandler as suffix to the logical name e.g.

    UnitButtonEventHandler.as).

    5. Writting group of variables and functions which are attached to _levels e.g._level0.doAction(strAction) (file should be named logically based on the

    group of functions written in the document with ATL(attached to level) as

    suffix to it e.g ActionHandler_ATL.as).6. Writing constant declarations (file should named logically with Const as

    suffix to it e.g. NavMsgConst.as).

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    7/32

    Release Notes Private and confidential Page 7 of 32

    Don't use nondescriptive names for methods or variablesFor example, if you retrieve a piece of data that is the visitor's user name, you

    might use the getUserName() method instead of the less descriptive getData()method.

    Keep all names as short as possible

    Short names enhance the application performance at run-time. But at the same

    time the name should be descriptive enough such that it can describe the purposeof the variable, function, class or file.

    3.2 Never use reserved words or language constructsWhen naming instances and variables, avoid using reserved words. Also, do not

    use any word in the ActionScript 2.0 languages (called a language construct) as

    an instance or variable name. ActionScript constructs include class names,component class names, method and property names, and interface names.

    Never use different cases to avoid conflicting with reserved words. For example,naming an instance of the textfield TextField class

    The following table lists reserved keywords in ActionScript 2.0 that cause errors inyour scripts when used as variable names:

    Add And break Case

    Catch class continue Default

    Delete Do dynamic Else

    Eq extends false Finally

    For function ge Get

    Gt If ifFrameLoaded implements

    Import In instanceof interface

    intrinsic Le it Ne

    New Not null On

    onClipEvent Or private Public

    Return Set static Super

    Switch tellTarget this Throw

    Try typeof var Void

    While With

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    8/32

    Release Notes Private and confidential Page 8 of 32

    The following words are reserved for future use in Flash, from the ECMAScript

    (ECMA-262) edition 4 draft language specifications. Avoid using these wordsbecause they might be used in future releases of Flash.

    As abstract Boolean Bytes

    Char const debugger Double

    Enum export final Float

    Goto Is long Namespace

    Native package protected Short

    synchronized throws transient Use

    Volatile

    3.3 Naming variablesName of variable should be able to tell the attributes of the variable. Typically the

    variable name should be able to provide following information about the variable.

    - Scope of the variable. Unless declared otherwise, all variables in a script areglobal. Though the global variable has advantage of being visible every where

    the use of global is discouraged over the local variable. Because the globalvariable are difficult to track and use more memory than the local variable as

    they persist through out the application life.

    Local variables must be explicitly declared, either as parameters to a function,or with the LOCAL statement.

    The variable should start with the scope definition. The following identifiers

    should be used for defining the scope of a variable:

    g_ - Global Variable

    c_ - Class/Static Variable_ - Member Variable

    - No prefix for a function parameter

    - No prefix for a local variable

    - Type of the variable. The following identifiers should be used for definingvariable type:

    str String - For string values (ranging from single character to longstring values)

    n Number - For all numerical values signed, unsigned, decimal or

    integer.b Boolean

    arr Array

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    9/32

    Release Notes Private and confidential Page 9 of 32

    obj Objectmc MovieClip

    tf TextField

    btn Button

    snd Soundcam Camera

    clr Color

    ctm ContextMenudt Dateerr Error

    lv LoadVars

    lc LocalConnectionmic Microphone

    mcl MovieClipLoader

    nc NetConnection

    ns NetStreampj PrintJob

    so SharedObjecttfss TextField.StyleSheettfmt TextFormat

    tss TextSnapshot

    vdo Video

    xml XMLxnd XMLNode

    xms XMLSocket

    Suggestion: We can maintain project specific document to maintain abbreviationspecification.

    - Name of the variable - Variable names can only contain letters, numbers,underscore (_) and dollar signs ($). Do not begin variable names withnumbers. Variables must be unique and they are case-sensitive in Flash Player

    7 and later. For example, avoid the following variable names://

    str/Warthog = true; // includes a slash

    str Warthogs = true; // includes a space

    str.Warthogs = true; // includes a dot

    5warthogs = 55; // begins with a number

    //

    Use the following guidelines when you name variables in your code:

    1. All variables must have unique names.2. Don't use the same variable name with different cases.3.

    Don't use words that are part of the ActionScript 1.0 or 2.0 languages asvariable names. In particular, never use keywords as instance names, because

    they cause errors in your code.4. Don't use variables that are parts of common programming constructs. For

    example, do not use the following keywords as variables://

    textfield = "myTextField";

    switch = true;

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    10/32

    Release Notes Private and confidential Page 10 of 32

    new = "funk";

    //

    - Use strict data typing with your variables when you are working in AS2.0

    Note - Strict data typing does not slow down a SWF file. Type checking occursat compile time (when the SWF file is created), not at runtime.

    5. Always add data type annotations to your code. Adding type annotations toyour variables is important in order to:

    - Generate errors at compile time so your application doesn't silently fail.- Trigger code completion.- Helps users understand your code.

    6. Don't overuse the Object type.7. Data type annotations should be precise to improve performance. Use an

    Object type only when there is no reasonable alternative.

    8. Keep variables as short as possible while retaining clarity.9. Make sure your variable names are descriptive, but don't go overboard and

    use overly complex and long names.10.Only use single-character variable names for optimization in loops. Optionally,

    you can use single-character variables for temporary variables in loops (suchas i, j, k, m, and n). Use these single-character variable names only for shortloop indexes, or when performance optimization and speed are critical. The

    following example shows this usage://

    var arrFont:Array = TextField.getFontList();

    arrFont.sort();

    var nLen = arrFont.length;

    var i:Number;

    for (i = 0; i < nLen; i++)

    {

    trace(arrFont[i]);

    }

    //

    11.Start variables with a lowercase letter.12.Names with capital first letters are reserved for classes, interfaces, and so on.13.Use mixed case for concatenated words. For example, use strFont instead of

    strfont.

    14.Don't use acronyms and abbreviations. The exception to this rule is ifacronyms or abbreviations represent the standard way to use a term (such as

    HTML or CFM). For commonly used acronyms, use mixed cases for improved

    readability, such as objHtmlParser instead of objHTMLParser.15.Use complementary pairs when you create a related set of variable names. For

    example:var nMinScore:Number = 10; // minimum score

    var nMaxScore:Number = 500; // maximum score

    3.4 Naming constantsYou can use constants for situations in which you need to refer to a property

    whose value never changes. This helps you find typographical mistakes in your

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    11/32

    Release Notes Private and confidential Page 11 of 32

    code that you might not find if you used literals. It also lets you change the valuein a single place. Use the following guidelines for naming static constants

    (variables that do not change):1. Constants should be uppercase.2. Separate words should contain underscores.3. Do not directly code numerical constants unless the constant is 1, 0, or -1,

    which you might use in a for loop as a counter value.//

    var BASE_URL:String = "http://www.macromedia.com"; // constant

    var MAX_WIDTH:Number = 10; // constant

    //

    3.5 Naming functions and methodsUse the following guidelines when you name functions and methods in your code.

    1. Use descriptive names.2. Use mixed case for concatenated words.3. Start function and method names with a lowercase letter.4. Describe what value is being returned in the function's name. For example,

    if you are returning the name of a song title, you should name the functiongetCurrentSong().

    5. Establish a naming standard for relating similar functions. ActionScript 2.0does not permit overloading.

    6. Name methods as verbs. You might concatenate the name, but it shouldcontain a verb. You use verbs for most methods because they perform an

    operation on an object. Examples of method names include the following:sing();

    boogie();

    singLoud();

    danceFast();

    getStudentName();setStudentName();

    7. Start methods which return Boolean value with the word "is" (because aBoolean value either "is" or "is not" because of its nature). For example://

    isGirl();

    //

    isLoggedIn();

    //

    3.6 Naming classes and objectsWhen you create a new class file, use the following guidelines when you name theclass and ActionScript file. For proper formatting, see the following examples of

    class names:class Widget;

    class PlasticWidget;

    class StreamingVideo;

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    12/32

    Release Notes Private and confidential Page 12 of 32

    You might have public and private member variables in a class. The class shouldalways contain private variables which cant be access directly. And allow the

    users to access the values only by using getter/setter methods.

    The following guidelines apply to naming classes:1. Begin a class name with an uppercase letter.2. Write class names in mixed case when it's a compound or concatenated word.3. Begin with an uppercase letter for a compound or concatenated word. A good

    example is NewMember.4. Class names are usually nouns or qualified nouns.5. A qualifier describes the noun or phrase. For example, instead of "member,"

    you might qualify the noun by using NewMember or OldMember.6. Clear names are more important than short names.7. Don't use acronyms and abbreviations. The exception to this rule is if

    acronyms or abbreviations represent the standard way to use a term (such as

    HTML or CFM). For commonly used acronyms, use mixed cases such asNewHtmlParser instead of NewHTMLParser for improved readability.

    8. Use meaningful and simple names that are descriptive of the class contents.9. To avoid being vague or misleading, use generic names.10.Sometimes a class name is a compound word.11.Do not pluralize the words you use in the class name (such as Witches or

    BaldPirates).

    12.Don't use a class name in the properties of that class because it causesredundancy.For example, it does not make sense to have Cat.catWhiskers.

    Instead, Cat.whiskers is much better.

    13.Don't use nouns that also might be interpreted as verbs.For example, Running, or Gardening. Using these nouns might lead toconfusion with methods, states, or other application activities.

    14.Use unique class names for each class in a single application.15.Do not name classes so that they conflict with the names of built-in classes in

    Flash.16.Try to communicate the relationship that a class has within a hierarchy. This

    helps display a class's relationship within an application. For example, youmight have the Widget interface, and the implementation of Widget might bePlasticWidget, SteelWidget, and SmallWidget.

    3.7 Naming packagesIt's common for package names to use "reverse domain" naming convention.Examples of reverse domain names include com.macromedia for

    macromedia.com, and org.yourdomain for yourdomain.org.

    Use the following guidelines when you name packages:

    1. Put the prefix for a package name in all lowercase letters.2. For example, com, mx, or org.3. Put related classes (classes with related functionality) in the same package.4. Begin package names with a consistent prefix.

    For example, you might use com.macromedia.projectName to maintain

    consistency. Another example would be com.macromedia.docs.learnAS2.5. Use a clear and self-explanatory package name.

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    13/32

    Release Notes Private and confidential Page 13 of 32

    6. It's important to explain the package's responsibilities. For example, youmight have a package named Pentagons, which is responsible for using the

    Flash drawing API to draw various kinds of pentagons in documentationexamples; its name would be com.macromedia.docs.as2.Pentagons.

    7. Use mixed capitalization for compound or concatenated package names.8. packageName is an example of a compound, concatenated package name.

    Remember to use all lowercase letters for the prefix (com, org, and so on).

    9. Do not use underscores or dollar sign characters.3.8 Naming interfacesStart interface names with an uppercase "I" as follows://

    interface IEmployeeRecord

    {}

    //

    The following conventions also apply:

    1. Interface names have an uppercase first letter.2. This is the same as class names.3. Interface names are usually adjectives. IPrintable is a good example.3.9 Naming custom componentsComponent names have an uppercase first letter, and any concatenated wordsare written in mixed case. To prevent naming incompatibilities with Macromediacomponents append the component name with MG (for Magic). For example, the

    following default user-interface component set uses concatenated words and

    mixed case:MGCheckBox

    MGComboBox

    MGDataGrid

    MGDateChooserMGDateField

    MGMenuBar

    MGNumericStepperMGProgressBar

    MGRadioButton

    MGScrollPaneMGTextAreaMGTextInput

    Components that do not use concatenated words begin with an uppercase letter.

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    14/32

    Release Notes Private and confidential Page 14 of 32

    4 Using comments in your codeUse comments consistently in your code. Comments must clearly explain the

    intent of the code and not just translate the code.

    Use the following guidelines when you add comments to your code:

    1. Use block comments (/* and */) for multi-line comments and single-linecomments ( // ) for short comments.

    2. You can also use a trailing comment on the same line as the ActionScript codeif necessary.

    3. Make sure you don't use comments to translate your ActionScript code.4. You don't need to comment on elements that are obvious in the ActionScript

    code.5. Comment on elements that are not readily obvious in the code.6. In particular, add comments when the subject is not described in the

    surrounding paragraphs.7. Do not use cluttered comments.8. A line of cluttered comments often contains equal signs (=) or asterisks (*).

    Instead, use white space or single-line comments (//) to separate yourcomments from ActionScript code.

    9. Remove any superfluous comments from the code before you deploy yourproject.

    10.If you find that you have many comments in your ActionScript code, considerwhether you need to rewrite some of it. If you feel you must include many

    comments about how the ActionScript code works, it is usually a sign of

    poorly written code.Example of good comments:

    /*

    TODO: NEENA - The onLoad event of the XML object does not invoke on Linux if

    the XML file doesnt exist. Need to discuss with GT for possible work around.*/

    //0 - prompt not played; 1 - prompt played; 2 - next clicked after prompt

    this.m_numUIDPrompt = 0;

    4.1 Adding comments to classesThe two kinds of comments in a typical class or interface file are documentation

    comments and implementation comments. You use documentation comments todescribe the code's specifications, but not the implementation. You use

    implementation comments to comment out code or to comment on the

    implementation of particular sections of code. Documentation comments aredelimited with /** and */, and implementation comments are delimited with /*

    and */.Use documentation comments to describe interfaces, classes, methods, andconstructors. Include one documentation comment per class, interface, or

    member, and place it directly before the declaration. If you have additional

    information to document that does not fit into the documentation comments, use

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    15/32

    Release Notes Private and confidential Page 15 of 32

    implementation comments (in the format of block comments or single-linecomments).

    Start classes with a standard comment. After the documentation comments,declare the class. Implementation comments should directly follow the

    declaration. Use block, single-line, and trailing comments within the body of yourclass to comment on your ActionScript code.

    The following example shows how you can write documentation comment for aclass. The detailed specification for documentation commenting is not in the scopeof this document and will be provided in a separate document.

    /**

    * An immutable, type-safe wrapper around the

    * String value of the user identifier.

    * The constructor will raise an exception if

    * the given value is not of the correct format,

    * asserting that the GUI validation code has

    * done its job, and preventing invalid data

    * being sent to the backend.

    ** @author Arthur Van Hoff

    * @version 1.0

    *

    * @see "some stuff"

    * @see some.OtherClass

    * @see some.OtherClass#field_name

    * @see some.OtherClass#method_name()

    */

    class com.mg.houseSeries.UserId

    {

    /**

    * Clears all data that has previously been

    * collected in this object, and returns it to

    * its initial state. Subclasses are expected

    * to override this method to clear any state of* their own, and use super() ensure that data

    * defined by this class is cleared too.

    */

    public function clear()

    {

    // ...

    }

    /**

    * For each value contained by this object, invoke

    * the given callback function, passing the value

    * as an argument.

    *

    * @param callback callback function to be invoked

    * for each object. The function must accept* one parameter (or two, if index is true).

    * @param index if true, each invocation of the

    * callback function will be passed an

    * additional second parameter giving the

    * index of the current value (starting with

    * 0 for the first value, 1 for the second,

    * and so on).

    * @param ... any additional arguments to be passed

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    16/32

    Release Notes Private and confidential Page 16 of 32

    * to the callback function.

    */

    public function invokeEach(objCallback:Function, bIndex:Boolean):Void

    {

    // ...

    }

    /**

    * Get the value corresponding to the given key

    * by searching in the local cache first, then

    * in the database on the LAN, and finally

    * consulting a number of LDAP servers from

    * around the wider internet.

    *

    * @return either the value for the given key, or

    * null if there is no such mapping.

    */

    public function get(strKey:String):String

    {

    // ...

    }

    }

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    17/32

    Release Notes Private and confidential Page 17 of 32

    5 ActionScript coding conventionsOne of the most important aspects about programming is consistency, whether it

    relates to variable naming schemes, formatting code, or coding standards and the

    placement of your code, which is covered in this section. You dramatically simplifycode debugging and maintenance if your code is organized and adheres tostandards.

    5.1 Keep your ActionScript code in one placePut code in a single location, such as in external ActionScript files or on Frame 1of the Timeline (when placed on the timeline, the code is called a frame script).

    If you put your ActionScript code in a frame script, put the ActionScript code onthe first or second frame on the Timeline, in a layer calledActions,which is the

    second layer on the Timeline the first layer is reserved for labels.Note: Do not write more then 15 lines of code in a frame script. Use external AS

    file if you have more code.

    5.2 Attaching code to objectsDo not attach ActionScript code to objects (such as button or movie clipinstances) in a FLA file, even in simple or prototype applications.

    This practice is strongly discouraged for the following reasons:

    1. ActionScript code that is attached to objects is difficult to locate, and the FLAfiles are difficult to edit and represents poor coding style.

    2. ActionScript code that is attached to objects is difficult to debug.3. ActionScript code that is written on a timeline or in classes is more elegant

    and easier to build upon.

    4. Attaching ActionScript code to a button called btnOk appears as follows. Avoidthis method://

    on (release)

    {

    // Do something.

    }

    //

    However, placing the equivalent ActionScript code on a timeline appears as

    follows://

    // good code

    btnOk.onRelease = function()

    {

    // Do something.

    };

    //

    5.3 Handling scopeIt is important to understand the difference between the global and root scopes.The root scope is unique for each loaded SWF file. The global scope applies to all

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    18/32

    Release Notes Private and confidential Page 18 of 32

    timelines and scopes within SWF files. You must use relative addressing ratherthan references to root timelines, because relative addressing makes the code

    reusable and portable.

    5.3.1 Do not use absolute targets (_root)Avoid using _root in ActionScript because SWF files that load into other SWF files

    might not work correctly. The _root identifier targets the base SWF file that isloading, not the SWF file using relative addressing instead of _root. This issue

    limits code portability in SWF files that are loaded into another file, and,particularly, in components and movie clips.

    Use this, this._parent, or _parent keywords rather than _root, depending onwhere your ActionScript code is located.

    5.3.2 Using the this keywordAlways use the this keyword as a prefix instead of omitting the keyword, even ifyour code works without it. Use the this keyword to learn when a method or

    property belongs to a particular class. For example, for a function on a timeline,you write ActionScript code by using the following format:mcCircleClip.onPress = function()

    {

    this.startDrag();

    };

    mcCircleClip.onRelease = function()

    {

    this.stopDrag();

    };

    For a class, use the following format to write code:class User

    {

    private var _strUserName:String;

    private var _strPassword:String;function User(strUserName:String, strPassword:String)

    {

    this._strUserName = strUserName;

    this._strPassword = strPassword;

    }

    public function get userName():String

    {

    return this._strUserName;

    }

    public function set userName(strUserName:String):Void

    {

    this._strUsername = strUserName;

    }

    }

    If you consistently add the this keyword in these situations, your ActionScriptcode will be much easier to read and understand.

    5.3.3 About scope in classesWhen you port code to ActionScript 2.0 classes, you might have to change how

    you use the this keyword. For example, if you have a class method that uses a

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    19/32

    Release Notes Private and confidential Page 19 of 32

    callback function (such as the LoadVars class's onLoad method), it can be difficultto know if the this keyword refers to the class or to the LoadVars object. In this

    situation, you might need to create a pointer to the current class, as the followingexample shows:

    class Product{

    private var _xmlProducts:XML;

    function Product(strTargetXml:String)

    {

    /*

    Create a local reference to the current class.Even if you are within

    the XML's onLoad event handler, you can reference the current class

    instead of only the XML packet.

    */

    var objThis:Product = this;

    // Create a local variable, which is used to load the XML file.

    var xmlProducts:XML = new XML();

    xmlProducts.ignoreWhite = true;

    xmlProducts.onLoad = function(bSuccess:Boolean)

    {

    if(bSuccess)

    {

    /*

    If the XML successfully loads and parses, set the class's

    _xmlProducts variable to the parsed XML document and call the

    init function.

    */

    objThis.init(this);

    }

    else

    {

    /* There was an error loading the XML file. */

    trace("error loading XML");

    }

    };

    // Begin loading the XML document

    xmlProducts.load(strTargetXml);

    }

    public function init(xmlProducts:XML):Void

    {

    this._xmlProducts = xmlProducts;

    // Display the XML packet

    trace(this._xmlProducts);

    }

    }

    Because you are trying to reference the private member variable within anonLoad handler, the this keyword actually refers to the xmlProducts instanceand not to the Product class, which you might expect. For this reason, you must

    create a pointer to the local class file so that you can directly reference the class

    from the onLoad handler.

    5.3.4 Structuring a class file

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    20/32

    Release Notes Private and confidential Page 20 of 32

    You have to create classes in separate ActionScript files that are imported orincluded (in AS 1.0) into a SWF file when it is compiled. The following conventions

    for structuring a class file show how you can order parts of a class to increase theefficiency and improve the readability of your code.

    To structure a class file, use the following elements:

    1. Add documentation comments that include a general description of the code,in addition to author information and version information. (Specification will beprovided in a separate document)

    2. Add your import or include statements (if applicable).3. Write a class declaration, or interface declaration, such as the following:

    Class HappyUser extends User{...}

    4. Include any necessary class or interface implementation comments. In thiscomment, add information that is pertinent for the entire class or interface.

    5. Add all your static variables if any. Write the public class variables first andfollow them with private class variables.

    6. Add instance variables. Write the public member variables first, and followthem with private member variables.7. Add the constructor statement, such as the one in the following example:public function HappyUser(strUsername:String, strPassword:String) {...}

    8. Write your methods.9. Group methods by their functionality, not by their accessibility or scope.

    Organizing methods this way helps to improve the readability and clarity of

    your code.10.Write the getter/setter methods into the class file.

    5.3.5 Guidelines for creating a classFollow these guidelines when you create a class file:1. Place only one declaration per line.2. Don't place multiple declarations on a single line.

    For example, format your declarations as shown in the following example:var nProdSku:Number; // Product SKU (identifying) number

    var nProdQuantity:Number; // Quantity of product

    This example shows better form than putting both declarations on a singleline. Place these declarations at the beginning of a block of code.

    3. Initialize local variables when they are declared.4. A class's properties should only be initialized in the declaration if the initializer

    is a compile-time constant.

    5. Declare variables before you first use them. This includes loops.6. Do not use local declarations that hide higher-level declarations.

    For example, don't declare a variable twice, as the following example shows:var nMaxLoop:Number = 0;

    function myMethod(){

    var nMaxLoop:Number = 10;

    for(var i = 0; nMaxLoop >= i; i++)

    {

    // statements;

    }

    }

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    21/32

    Release Notes Private and confidential Page 21 of 32

    This code declares the same variable inside an inner block, which is a practiceto avoid.

    7. Don't assign many variables to a single value in a statement.8. Set the member variables to private unless you have a good reason for

    making them public. From a design standpoint, it is much better to makemember variables private and allow access to those variables through a group

    of getter/setter functions only.

    9. You can also use a class name prefix for static variables and methods, evenwithin a class. This helps qualify the references you make. Depending on whatcoding environment you are using, your prefixes might also trigger code

    completion and hinting. The following code demonstrates prefixing a static

    property with a class name:class Widget

    {

    public static var c_nWidgetCount:Number = 0;

    public function Widget()

    {

    Widget.c_nWidgetCount++;

    }}

    5.3.6 About initializationFor the initial values for variables, assign a default value or allow the value of

    undefined. When you initialize properties inline, the expression on the right side of

    an assignment must be a compile-time constant. Compile-time constants includestring literals, numbers, Boolean values, null, and undefined, as well as

    constructor functions for the following top-level classes: Array, Boolean, Number,Object, and String. This class sets the initial values of _strUserName and

    _strPassword to empty strings:class User

    { private var _strUserName:String = "";

    private var _strPassword:String = "";

    function User(strUserName:String, strPassword:String)

    {

    this._strUserName = strUserName;

    this._strPassword = strPassword;

    }

    }

    Delete variables or make variables null when you no longer need them. Settingvariables to null can still enhance performance. This process is commonly called

    garbage collection. Deleting variables helps optimize memory usage duringruntime, because unneeded assets are removed from the SWF file. It is better to

    delete variables than to set them to null.

    Note: Flash Player 8 has made improvements in garbage collection within FlashPlayer.

    You can encapsulate all your initialization for an instance within the class's

    constructor function, or abstract it into a separate method, which you wouldexplicitly call after the variable is created, as the following code shows:class User

    {

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    22/32

    Release Notes Private and confidential Page 22 of 32

    private var _strUserName:String;

    private var _strPassword:String;

    private var _nCount:Number;

    function User(strUserName:String, strPassword:String)

    {

    this._strUsername = strUsername;

    this._strPassword = strPassword;

    this._nCount = 0;

    }

    }

    5.3.7 Use trace statementsUse trace statements in your documents to help you debug your code while

    authoring the FLA file. For example, by using a trace statement and for loop, youcan see the values of variables in the Output panel, such as strings, arrays, and

    objects. Using a trace statement is an efficient way to debug your ActionScript

    2.0. Before you publish a SWF file, open Publish Settings and select Omit TraceActions on the Flash tab.

    Note: Even though Flash provide the option to remove the trace statements using

    publish settings this is mandatory for every one to remove all trace statementsafter finishing their part of coding and before checking in on VSS.

    5.3.8 About the super prefixIf you refer to a method in the parent class, prefix the method with super. Thefollowing ActionScript 2.0 snippet demonstrates the use of proper scoping byusing the super prefix:

    In the following example, you create two classes. You use the super keyword in

    the Socks class to call functions in the parent class (Cloth). Although both the

    Socks and Clothes classes have a method called getColor(), using super lets youspecifically reference the base class's methods and properties. Create a new AS

    file called Cloth.as, and enter the following code:class Cloth

    {

    private var _strColor:String;

    function Cloth(strParamColor:String)

    {

    this._strColor = strParamColor;

    trace("[Cloth] I am the constructor");

    }

    function getColor():String

    {

    trace("[Cloth] I am getColor");

    return this._strColor;

    }

    function setColor(strParamColor:String):Void

    {

    this._strColor = strParamColor;

    trace("[Cloth] I am setColor");

    }

    }

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    23/32

    Release Notes Private and confidential Page 23 of 32

    Create a new class called Socks that extends the Clothes class, as shown in thefollowing example:class Socks extends Cloth

    {

    private var _strColor:String;

    function Socks(strParamColor:String){

    this._strColor = strParamColor;

    trace("[Socks] I am the constructor");

    }

    function getColor():String

    {

    trace("[Socks] I am getColor");

    return super.getColor();

    }

    function setColor(strParamColor:String):Void

    {

    this._strColor = strParamColor;

    trace("[Socks] I am setColor");

    }

    }Then create a new AS or FLA file and enter the following ActionScript in the

    document:import Socks;

    var objSock:Socks = new Socks("maroon");

    trace(" -> " + objSock.getColor());

    objSock.setColor("Orange");

    trace(" -> " + objSock.getColor());

    The following result is displayed in the Output panel:[Cloth] I am the constructor

    [Socks] I am the constructor

    [Socks] I am getColor

    [Cloth] I am getColor

    -> maroon

    [Socks] I am setColor

    [Socks] I am getColor

    [Cloth] I am getColor

    -> Orange

    If you forgot to put the super keyword in the Socks class's getColor() method, the

    getColor() method could call itself repeatedly, which would cause the script to fail

    because of infinite recursion problems. The Output panel would display thefollowing error if you didn't use the super keyword:[Cloth] I am the constructor

    [Socks] I am the constructor[Socks] I am getColor

    [Socks] I am getColor

    ...

    [Socks] I am getColor256 levels of recursion were exceeded in one action list.

    This is probably an infinite loop.

    Further execution of actions has been disabled in this SWF file.

    5.3.9 Do not use the with statementConsider the following code that uses the with statement:

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    24/32

    Release Notes Private and confidential Page 24 of 32

    this.attachMovie("mcCircleClip", "mcCircleClip", 1);

    with (mcCircleClip)

    {

    _x = 20;

    _y = Math.round(Math.random()*20);

    _alpha = 15;

    createTextField("tfLabelTxt", 100, 0, 20, 100, 22);

    tfLabelTxt.text = "Circle 1";

    }

    It is easier to follow what is happening in your code if you explicitly specify the

    variables scope, instead of relying on the with statement. The following exampleshows a slightly longer, but better, ActionScript example that specifies the

    variables scope:this.attachMovie("mcCircleClip", " mcCircleClip", 1);

    mcCircleClip._x = 20;

    mcCircleClip._y = Math.round(Math.random()*20);

    mcCircleClip._alpha = 15;

    mcCircleClip.createTextField("tfLabelTxt", 100, 0, 20, 100, 22);

    mcCircleClip.tfLabelTxt.text = "Circle 1";

    5.3.10About using functionsCreate a function for each blocks of code which is being used more that once. This

    way you can reuse code by calling a function multiple times, instead of creatingdifferent code each time. Functions should be generic pieces of code; such that,

    you can use the same blocks of code for slightly different purposes in a SWF file.

    Reusing code lets you create efficient applications and minimize the code that youmust write, which reduces development time. You should always create a functionin a class file, or write ActionScript that resides in a code-based component, on in

    a external AS file.

    class Circle

    { public function area(nRadius:Number):Number

    {

    return (Math.PI*Math.pow(nRadius, 2));

    }

    public function perimeter(nRadius:Number):Number

    {

    return (2 * Math.PI * nRadius);

    }

    public function diameter(nRadius:Number):Number {

    return (nRadius * 2);

    }

    }

    Put functions into a class file. This is a best practice when you choose to use

    ActionScript 2.0, because it maximizes code reusability. To reuse the functions inother applications, import the existing class rather than rewrite the code from

    scratch, or duplicate the functions in the new application.

    5.3.11Stop code repetition

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    25/32

    Release Notes Private and confidential Page 25 of 32

    The onEnterFrame event handler is useful because Flash can use it to repeat codeat the frame rate of a SWF file. However, this behavior can cause performance

    problems on computers that play the SWF file. If you use the onEnterFrame eventhandler for any kind of animation or repetition in your SWF files, delete the

    onEnterFrame handler when you finish using it. In the following ActionScript 2.0code, you stop repetition by deleting the onEnterFrame event handler:mcCircleClip.onEnterFrame = function() {

    mcCircleClip._alpha -= 5;

    if (mcCircleClip._alpha

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    26/32

    Release Notes Private and confidential Page 26 of 32

    6 ActionScript and Flash Player optimizationNote: If you compile a SWF file that contains ActionScript 2.0 with publish settings set

    to Flash Player 6 and ActionScript 1.0, your code functions as long as it does not use

    ActionScript 2.0 classes. No case sensitivity is involved with the code, only FlashPlayer. Therefore, if you compile your SWF file with Publish Settings set to Flash Player7 or 8 and ActionScript 1.0, Flash enforces case sensitivity. Data type annotations

    (strict data types) are enforced at compile time for Flash Player 7 and 8 when you havepublish settings set to ActionScript 2.0.ActionScript 2.0 compiles to ActionScript 1.0 bytecode when you publish your

    applications, so you can target Flash Player 6, 7, or 8 while working with ActionScript

    2.0.

    6.1 Optimize your codeFollow these guidelines to optimize your code:

    1. Avoid calling a function multiple times from within a loop. It is better to includethe contents of a small function inside the loop.

    2. Use native functions (function available with the Flash) when possible. Nativefunctions are faster than user-defined functions.

    3. Don't overuse the Object type.4. Data-type annotations should be precise, because it improves performance.

    Use the Object type only when there is no reasonable alternative.

    5. Do not use the eval() function or array access operator e.g._root[mc1].6. Set the local reference once to make code more efficient. Assign the

    Array.length to a variable before a loop. Assign Array.length to a variablebefore a loop to use as its condition, rather than using myArr.length itself. For

    example,var arrFont:Array = TextField.getFontList();

    var nArrayLen:Number = arrFont.length;

    for (var i:Number = 0; i < nArrayLen; i++)

    {trace(arrFont[i]);

    }

    instead of:var arrFont:Array = TextField.getFontList();

    for (var i:Number = 0; i < arrFont.length; i++)

    {

    trace(arrFont[i]);

    }

    7. Optimizing loops, there should not be any repeating actions. Flash Playerspends a lot of time processing loops (such as those that use the setInterval()

    function).8. Add the var keyword when declaring a variable.9. Don't use class variables or global variables when local variables will suffice.

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    27/32

    Release Notes Private and confidential Page 27 of 32

    7 Formatting ActionScript syntaxFormatting ActionScript 2.0 code in a standardized way is essential to writing maintainablecode.

    7.1 General formatting guidelinesWhen you use spaces, line breaks, and tab indents to add white space to your code,you increase your code's readability.Follow these guidelines for formatting your code:

    1. Put one blank line between paragraphs (modules) of ActionScript. Paragraphs ofActionScript code are groups of logically related code.

    2. Use consistent indentation as specified later in this document in your code to helpshow the hierarchy of the code's structure. Use the same indentation style

    throughout your ActionScript code, and make sure that you align the braces ({})properly.

    3. Use line breaks to make complex statements easier to read.4. Formatting long statements across several lines rather than across a single line.

    E.g.strQueryString = strURL

    + ?UID= + strUserID

    + &USERNAME= + strUserName

    + &TOT= + numTOT

    + &BOOKMARK= + strBookmark

    + &SCORE= + numScore;

    5. Always write code before after the opening and closing curly braces [{}]. Include aspace after a keyword that is followed by parentheses [()]. The following

    ActionScript code shows some example of this:do

    {

    // something

    }while (condition);

    Orif (blnSuccess)

    {

    // something

    }

    Orfunction addUser(in_strUserName)

    {

    // something

    }

    Orclass IntervalManager

    {// class definition

    }

    6. Don't put a space between a method name and parentheses. For example,function checkLogin()

    {

    // something

    }

    checkLogin();

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    28/32

    Release Notes Private and confidential Page 28 of 32

    7. Include a space after commas in a list of arguments. For example,function addItems(nItem1:Number, nItem2:Number):Number

    {

    return (nItem1 + nItem2);

    }

    var nSum:Number = addItems(1, 3);

    8. Use spaces to separate all operators and their operands.//good

    var nSum:Number = 7 + 3;

    //bad

    var nSum:Number=7+3;

    The only exception to this guideline is the dot (.) operator.9. Don't include a space between unary operators and their operands. For example:

    while (d++ = s++)

    10.Don't include spaces after an opening parenthesis and before a closingparenthesis. The following ActionScript code shows an example of this://bad

    ( "size is " + foo + "\n" );

    //good

    ("size is " + foo + "\n");

    11.Put each statement on a separate line to increase the readability of yourActionScript code:nCount++; // Correct

    nCountUser++; // Correct

    nCount++; nCountUser++; // Incorrect

    12.Don't embed assignments. Embedded statements are sometimes used to improveperformance in a SWF file at runtime, but the code is much harder to read anddebug. The following ActionScript code shows an example of this (but remember to

    avoid single-character naming in the actual code):var nMyNum:Number = (a = b + c) + d;

    Assign variables as separate statements.var nNum:Number = b + c;

    var nMyNum:Number = nNum + d;

    13.Break a line before an operator.14.Break a line after a comma.15.Align the second line with the start of the expression on the previous line of code.7.2 Writing conditional statementsFollow these guidelines when you write conditional statements:1. Place conditions on separate lines in if, else..if, and if..else statements. Use braces

    ({}) for if statements. Format braces as shown in the following examples:// if statement

    if (condition)

    {

    // statements

    }

    // if..else statement

    if (condition)

    {

    // statements

    }

    else

    {

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    29/32

    Release Notes Private and confidential Page 29 of 32

    // statements

    }

    // else..if statement

    if (condition)

    {

    // statements

    }

    else if (condition)

    {

    // statements

    }

    else

    {

    // statements

    }

    2. Use parentheses [()] to group conditions in complex conditions. For example,if ((fruit == apple) && (veggie == leek)) {}

    3. You can write a conditional statement that returns a Boolean value in two ways

    if (arrCart.length > 0){

    return true;

    }

    else

    {

    return false;

    }

    Compare this example with the previous one:// better

    return (arrCart.length > 0);

    The second snippet is shorter and has fewer expressions to evaluate.4. You can use conditional operators as below:

    return ((y > 0) ? x / y : 0);

    7.3 Writing compound statementsCompound statements contain a list of statements within braces ({}). The statements

    within these braces are indented from the compound statement. The followingActionScript code shows an example of this:if (a == b)

    {

    // This code is indented.

    trace("a == b");

    }

    Place braces around each statement when it is part of a control structure (if..else or

    for), even if it contains only a single statement. The following example shows code that

    is written poorly:// bad

    if (nUsers == 0)

    trace("no users found.");

    Although this code validates, it is poorly written because it lacks braces around the

    statements. In this case, if you add another statement after the trace statement, the

    code executes regardless of whether the nUsers variable equals 0:// bad

    var nUsers:Number = 5;

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    30/32

    Release Notes Private and confidential Page 30 of 32

    if (nUsers == 0)

    trace("no users found.");

    trace("I will execute");

    Executing the code despite the nUsers variable can lead to unexpected results. For thisreason, add braces, as shown in the following example:

    var nUsers:Number = 0;if (nUsers == 0)

    {

    trace("no users found");

    }

    When you write a condition, don't add the redundant ==true in your code, as follows:if (something == true)

    {

    //statements

    }

    If you are compare against false, you could use if (something==false) orif(!something).

    7.4 Writing a for statementWrite the for statement using the following format:for (init; condition; update)

    {

    // statements

    }

    The following structure demonstrates the for statement:var i:Number;

    for (i = 0; i < 4; i++)

    {

    mcMyClip.duplicateMovieClip("mcClip" + i, i + 10);

    }

    Remember to include a space following each expression in a for statement.

    7.5 Writing while and do..while statementsWrite while statements using the following format:while (condition)

    {

    // statements

    }

    And do-while statements using the following format:do

    {

    // statements

    }

    while (condition);

    7.6 Writing return statementsDon't use parentheses [()] with any return statements that have values. The only timeto use parentheses with return statements is when they make the value more obvious,

    as shown in the third line of the following ActionScript code snippet:return;

    return objCar.strPaintColor;

    // parentheses used to make the return value obvious

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    31/32

    Release Notes Private and confidential Page 31 of 32

    return ((strPaintColor)? strPaintColor: strDefaultColor);

    7.7 Writing switch statementsAll switch statements include a default case. The default case is the last case in aswitch statement. The default case includes a break statement that prevents a fall-through error if another case is added. If a case does not have a break statement, the

    case will fall through (see case A in the following code example). Your statement

    should include a comment in the break statement's place, as you can see in thefollowing example after case A. In this example, if the condition matches case A, bothcases A and B execute.

    Write switch statements using the following format:switch (condition)

    {

    case A :

    // statements

    // falls through

    case B :

    // statementsbreak;

    case Z :

    // statements

    break;

    default :

    // statements

    break;

    }

    7.8 Writing try..catch and try..catch..finally statementsWrite try..catch and try..catch..finally statements using the following formats:var errObject:Error;

    // try..catch

    try{

    // statements

    }

    catch (errObject)

    {

    // statements

    }

    // try..catch..finally

    try

    {

    // statements

    }

    catch (errObject)

    { // statements

    }

    finally

    {

    // statements

    }

  • 8/3/2019 Best Practices Coding Conventions as v1.1

    32/32

    7.9 Using listener syntaxThe example shows a properly formatted listener syntax, which uses a Loader

    component to load content into a SWF file. The progress event starts when contentloads, and the complete event indicates when loading finishes.

    var ldrBox:mx.controls.Loader;var ldrListener:Object = new Object();

    ldrListener.progress = function(objEvt:Object)

    {

    trace("loader loading:" + Math.round(objEvt.target.percentLoaded) + "%");

    };

    ldrListener.complete = function(objEvt:Object)

    {

    trace("loader complete:" + objEvt.target._name);

    };

    ldrBox.addEventListener("progress", ldrListener);

    ldrBox.addEventListener("complete", ldrListener);

    ldrBox.load("https://reader009.{domain}/reader009/html5/0507/5af0014586488/5af0015be8

    A slight variation on the first example in this section is to use the handleEvent method,

    but this technique is slightly more cumbersome and this technique is notrecommended because you must use a series of if..else statements or a switch

    statement to detect which event is caught.var ldrBox:mx.controls.Loader;-

    var ldrListener:Object = new Object();

    ldrListener.handleEvent = function(objEvt:Object)

    {

    switch (objEvt.type)

    {

    case "progress" :

    trace("loader loading:" + Math.round(objEvt.target.percentLoaded) +

    "%");

    break;

    case "complete" :trace("loader complete:" + objEvt.target._name);

    break;

    }

    };

    ldrBox.addEventListener("progress", ldrListener);

    ldrBox.addEventListener("complete", ldrListener);

    ldrBox.load("https://reader009.{domain}/reader009/html5/0507/5af0014586488/5af0015be8