• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Flash coding convention for action script 3
 

Flash coding convention for action script 3

on

  • 7,321 views

 

Statistics

Views

Total Views
7,321
Views on SlideShare
6,902
Embed Views
419

Actions

Likes
1
Downloads
0
Comments
0

2 Embeds 419

http://minhtan.wordpress.com 417
http://moodle.suffolkone.org 2

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Flash coding convention for action script 3 Flash coding convention for action script 3 Document Transcript

    • Flash Coding Convention for Action Script 3.0 [Collected by Tan Tran, Logigear, DS team]Ref links:http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001091.html#wp280349http://opensource.adobe.com/wiki/display/flexsdk/Coding+Conventionshttp://livedocs.adobe.com/flex/3/html/help.html?content=asdoc_3.html
    • Table of ContentsNaming Conventions ..................................................................................................... 4 Abbreviations .......................................................................................................................................... 4 Avoiding reserved words and language constructs ................................................................................... 5 Acronyms ................................................................................................................................................ 5 Word boundaries ...................................................................................................................................... 5 Package names ......................................................................................................................................... 6 File names ............................................................................................................................................... 6 Namespace names .................................................................................................................................... 6 Interface names ........................................................................................................................................ 6 Class names ............................................................................................................................................. 6 Event names ............................................................................................................................................ 7 Style names.............................................................................................................................................. 7 Enumerated values for String properties ................................................................................................... 7 Constant names ........................................................................................................................................ 7 Property (variable and getter/setter) names ............................................................................................... 7 Getter/setter variable names ..................................................................................................................... 7 Storage variable names ............................................................................................................................ 7 Place Getter/setter method ....................................................................................................................... 8 Method names ......................................................................................................................................... 8 Method names should always be verbs. .................................................................................................... 8 Event handler names ................................................................................................................................ 8 Argument names ...................................................................................................................................... 8 Resource bundle names ............................................................................................................................ 9 Resource key names ................................................................................................................................. 9 Miscellaneous nomenclature .................................................................................................................... 9 Naming Boolean variables ....................................................................................................................... 9 Naming custom components .................................................................................................................... 9ActionScript Coding Expressions .............................................................................. 10 Type declarations ................................................................................................................................... 10 Literals................................................................................................................................................... 10 undefined ................................................................................................................................................. 10 int and uint literals .................................................................................................................................. 11 Number literals ....................................................................................................................................... 11 String literals .......................................................................................................................................... 12 Array literals ........................................................................................................................................... 12 Object literals.......................................................................................................................................... 12 Function literals ...................................................................................................................................... 13 RegExp literals ........................................................................................................................................ 13 XML and XMLList literals ...................................................................................................................... 13 Class literals ........................................................................................................................................... 13 Parentheses ............................................................................................................................................ 14 Coercion ................................................................................................................................................ 14 Comparison ........................................................................................................................................... 15 ++ and -- operators................................................................................................................................. 15 Ternary operator .................................................................................................................................... 15 new operator .......................................................................................................................................... 15 Statements ............................................................................................................................................. 16 include statements .................................................................................................................................. 16 Page 2/27
    • import statements ................................................................................................................................... 16 use namespace statements ...................................................................................................................... 16 if statements ........................................................................................................................................... 17 for statements......................................................................................................................................... 18 while statements..................................................................................................................................... 19 do statements ......................................................................................................................................... 19 switch statements ................................................................................................................................... 19 Declarations ........................................................................................................................................... 21 The override keyword ............................................................................................................................ 21 Access specifiers .................................................................................................................................... 21 The static keyword ................................................................................................................................. 21 The final keyword .................................................................................................................................. 21 Constants ............................................................................................................................................... 21 Variables................................................................................................................................................ 22 Local variables ....................................................................................................................................... 22 Classes ................................................................................................................................................... 23 Constructors........................................................................................................................................... 24 Line width ............................................................................................................................................. 24ActionScript Comments .............................................................................................. 25 Creating ASDoc comments .................................................................................................................... 25 Writing an ASDoc comment .................................................................................................................. 25 Placing ASDoc comments ...................................................................................................................... 25 Formatting ASDoc comments ................................................................................................................ 26 Using the @private tag........................................................................................................................... 27 Excluding an inherited element .............................................................................................................. 27 Using HTML tags .................................................................................................................................. 27 Using special characters ......................................................................................................................... 28 Hiding text in ASDoc comments ............................................................................................................ 28 Rules for parsing ASDoc comments ....................................................................................................... 28Organize ActionScript Classes ................................................................................... 30 Page 3/27
    • Naming ConventionsChoosing good names is critical to creating code that is easy to use and easy to understand. You shouldalways take the time to think about whether you have chosen the right name for something, especially if it ispart of the public API.Our naming standards are mostly consistent with those of ECMAScript and Flash Player 9.Choosing good names is critical to creating code that is easy to use and easy to understand. You shouldalways take the time to think about whether you have chosen the right name for something, especially if it ispart of the public API.Our naming standards are mostly consistent with those of ECMAScript and Flash Player 9.AbbreviationsAvoid them as a general rule. For example, calculateOptimalValue() is a better method name thancalcOptVal().Being clear is more important than minimizing keystrokes. And if you dont abbreviate, developers wonthave to remember whether you shortened a word like “qualified” to “qual” or “qlfd”.However, we have standardized on a few abbreviations: acc for accessibility, as in ButtonAccImpl auto for automatic, as in autoLayout auto for automatic, as in autoLayout eval for evaluate, as in EvalBindingResponder impl for implementation, as in ButtonAccImpl info for information, as in GridRowInfo num for number of, as in numChildren min for minimum, as in minWidth max for maximum, as in maxHeight nav for navigation, as in NavBar regexp for regular expression, as in RegExpValidator util for utility, as in StringUtilThis list probably does not include all abbreviations that are currently in use. If youre considering using anabbreviation that isnt listed here, please search the source code to determine whether it is already in use. Ifyou dont find it, think twice about whether abbreviating is really appropriate.Occasionally we are (deliberately) inconsistent about abbreviations. For example, we spell out “horizontal”and “vertical” in most places, such as horizontalScrollPolicy and verticalScrollPolicy but we abbreviatethem to H and V in the very-commonly-used container names HBox and VBox. Page 4/27
    • Avoiding reserved words and language constructsThe following table lists reserved keywords in ActionScript that cause errors in your scripts when used asvariable 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 undefined var void while withThe following words are reserved for future use in Flash, from the ECMAScript (ECMA-262) edition 4draft language specification. Avoid using these words because they might be used in future releases ofFlash. as abstract Boolean bytes char const debugger double enum export final float goto is long namespace native package protected short synchronized throws transient use volatileAcronymsVarious acronyms are common in Flex, such as AIR, CSS, HLOC, IME, MX, MXML, RPC, RSL, SWF,UI, UID, URL, WSDL, and XML.An acronym is always all-uppercase or all-lowercase (e.g., SWF or swf, but never Swf). The only time thatall-lowercase is used is when the acronym is used by itself as an identifier, or at the beginning of anidentifier, and the identifier should start with a lowercase letter. See the rules below for which identifiersshould start with which case.Examples of identifiers with acronyms are CSSStyleDeclaration, IUID, uid, IIME, and imeMode.Word boundariesWhen an identifier contains multiple words, we use two ways of indicating word boundaries: intercaps (asin LayoutManager or measuredWidth) and underscores (as in object_proxy). See the rules below for whichmethod to use.Sometimes it isnt clear whether a word combination has become its own single word, and we areunforunately inconsistent about this in some places: dropdown, popUp, pulldown.Follow the acronym-casing rules even in the rare case that two acronyms must be adjacent. An example(which isnt actually in use) would be something like loadCSSURL(). But try to avoid such names. Page 5/27
    • Package namesStart them with a lowercase letter and use intercaps for subsequent words: controls, listClasses.Package names should always be nouns or gerunds (the -ing noun form of a verb), not verbs, adjectives, oradverbs.A package implementing lots of similar things should have a name which is the plural form of the thing:charts, collections, containers, controls, effects, events, formatters, managers, preloaders, resources, skins,states, styles, utils, validators.It is common to use a gerund for the name of a package which implements a concept: binding, logging,messaging, printing. Otherwise, they are generally "concept nouns": accessibility, core, graphics, rpc.A package containing classes that support component FooBar should be called fooBarClasses.File namesFor importable APIs, the file name must be the same as the public API inside. But include files dont have tofollow this rule.Start the names of include files for [Style(...)] metadata with an uppercase letter, use intercaps forsubsequent words, and make the last word “Styles”: BorderStyles.as, ModalTransparencyStyles.as.Start the names of individual asset files with a lowercase letter and use underscores between words:icon_align_left.png.Namespace namesStart them with a lowercase letter and use underscores between words: mx_internal, object_proxy.Interface namesStart them with I and use intercaps for subsequent words: IList, IFocusManager, IUID.Class namesStart them with an uppercase letter and use intercaps for subsequent words: Button, FocusManager,UIComponent.Name Event subclasses FooBarEvent.Name Error subclasses FooBarError.Name the EffectInstance subclass associated with effect FooBar FooBarInstance.Name Formatter subclasses FooBarFormatter.Name Validator subclasses FooBarValidator.Name skinning classes FooBarBackground, FooBarBorder, FooBarSkin, FooBarIcon, FooBarIndicator,FooBarSeparator, FooBarCursor, etc.Name utility classes FooBarUtil (not FooBarUtils; the package is plural but the class is singular).It is common to name a base class FooBarBase: ComboBase, DateBase, DataGridBase, ListBase. Page 6/27
    • Event namesStart them with a lowercase letter and use intercaps for subsequent words: "move", "creationComplete".Style namesStart them with a lowercase letter and use intercaps for subsequent words: color, fontSize.Enumerated values for String propertiesStart them with a lowercase letter and use intercaps for subsequent words: "auto", "filesOnly",Constant namesUse all uppercase letters with underscores between words: OFF, DEFAULT_WIDTH.The words in the identifier must match the words in the constant value if it is a String: public static const FOO_BAR:String = "fooBar";Property (variable and getter/setter) namesStart them with a lowercase letter and use intercaps for subsequent words: i, width, numChildren.Use i for a loop index and n for its upper limit. Use j for an inner loop index and m for its upper limit. for (var i:int = 0; i < n; i++) { for (var j:int = 0; j < m; j++) { ... } }Use p (for “property”) for a for-in loop variable: for (var p:String in o) { ... }If a class overrides a getter/setter and wants to continue to expose the base getter/setter, it should do so byimplementing a property whose name is the base name with a $ prepended. This getter/setter should bemarked final and should do nothing more than call the supergetter/setter. mx_internal final function get $numChildren():int { return super.numChildren; }Getter/setter variable namesPrefix variables with underscores for getter/settersPrefix variables with an underscore if they will be modified through getter/setter methodsStorage variable namesGive the storage variable for the getter/setter foo the name _foo. Page 7/27
    • Place Getter/setter methodPlace the getter method above the setter methodWhen creating getter/setter methods place the getter method firstMethod namesStart them with a lowercase letter and use intercaps for subsequent words: measure(), updateDisplayList().Method names should always be verbs.Parameterless methods should generally not be named getFooBar() or setFooBar(); these should beimplemented as getter/setters instead. However, if getFooBar() is a slow method requiring a large amount ofcomputation, it should be named findFooBar(), calculateFooBar(), determineFooBar(), etc. to suggest this,rather than being a getter.If a class overrides a method and wants to continue to expose the base method, it should do so byimplementing a method whose name is the base name with a $ prepended. This method should be markedfinal and should do nothing more than call the supermethod. mx_internal final function $addChild(child:DisplayObject):DisplayObject { return super.addChild(child); }Event handler namesEvent handlers should be named by concatenating “Handler” to the type of the event:mouseDownHandler().If the handler is for events dispatched by a subcomponent (i.e., not this), prefix the handler name with thesubcomponent name and an underscore: textInput_focusInHandler().Argument namesUse value for the argument of every setter:Do this: public function set label(value:String):voidNot this: public function set label(lab:String):voidOr this: public function set label(labelValue:String):voidOr this: public function set label(val:String):voidUse event (not e, evt, or eventObj) for the argument of every event handler: protected function mouseDownHandler(event:Event):void Page 8/27
    • Resource bundle namesIf a resource bundle contains resources for a particular package, name the bundle the same as the package:controls, {formatters}}, validators.Resource key namesStart them with a lowercase letter and use intercaps for subsequent words: pm, dayNamesShort.Miscellaneous nomenclatureAvoid “object” because it is vague.An “item” is a data item, not a DisplayObject.A “renderer” is a DisplayObject that displays a data item.A “type” is an AS3 type; use "kind" otherwise.Naming Boolean variablesStart Boolean variables with the word "is" (because a Boolean value either "is" or "is not" because of itsnature). Therefore, you might use the following for whether a baby is a girl or not (which is a Booleanvalue): isGirl Or for a variable indicating whether a user is logged in (or not), you might use the following:isLoggedIn.Naming custom componentsComponent names have an uppercase first letter, and any concatenated words are written in mixed case. Forexample, the following default user-interface component set uses concatenated words and mixed case: • CheckBox • ComboBox • DataGrid • DateChooser • DateField • MenuBar • NumericStepper • ProgressBar • RadioButton • ScrollPane • TextArea • TextInputComponents that do not use concatenated words begin with an uppercase letter.If you develop custom components, use a naming convention to prevent naming incompatibilities withAdobe components. The names of your components must be different from those of the default set that isincluded with Flash. If you adopt your own consistent naming convention, it helps you prevent namingconflicts.Remember that the naming conventions in this section are guidelines. It is most important to use a namingscheme that works well for you and to use it consistently. Page 9/27
    • ActionScript Coding ExpressionsThis section discusses how we use the language constructs of ActionScript 3, especially when there aremultiple ways to express the same thing.Type declarationsWrite a type annotation for every constant, variable, function argument, and function return value, even ifthe annotation is simply :* to indicate “no type”.Do this: var value:*;Not this: var value;Use the narrowest type that is appropriate. For example, a loop index should be a int, not a Number, andcertainly not an Object or *. As another example, a mouseDownHandler should declare its argument asevent:MouseEvent, not event:Event.Use int for integers, even if they cant be negative. Use uint only for RGB colors, bit masks, and other non-numeric values.Use * only if the value can be undefined. You should generally use Object rather than *, with null being the“object doesnt exist” value.If you declare something to be of type Array, add a comment of the form /* of ElementType */ immediatelyafter Array indicate the type of the array elements. A future version of the language is likely to have typedarrays.Do this: var a:Array /* of String */ = [];Not this: var a:Array = [];And this: function f(a:Array /* of Number */):Array /* of Object */ { ... }Not this: function f(a:Array):Array;LiteralsundefinedAvoid using this when possible. It is only necessary when dealing with values whose compile-time is type is*, and you should be using * sparingly as well. Page 10/27
    • int and uint literalsDo not use a decimal point in a integer.Do this: 2Not this: 2.Use a lowercase x and uppercase A-Z in hexadecimal numbers.Do this: 0xFEDCBANot this: 0XfedcbaAlways write an RGB color as a six-digit hexadecimal number.Do this: private const BLACK:uint = 0x000000;Not this: private const BLACK:uint = 0;When dealing with indices, use the value -1 to mean “no index”.Number literalsIf a Number value typically can be fractional, indicate this by using a decimal point, and follow the decimalpoint by a single trailing zero.Do this: alphaFrom = 0.0; alphaTo = 1.0;Not this: alphaFrom = 0; alphaTo = 1;However, dont do this for pixel coordinates, which are by convention integral even though they can inprinciple be fractional.Do this: var xOffset:Number = 3;Not this: var xOffset:Number = 3.0;Use e, not E, when using exponential notation.Do this: 1.0e12Not this: 1.0E12Use the default value NaN as the “not set” value for a Number. Page 11/27
    • String literalsUse quotation marks (double quotes), not apostrophes (single quotes), to delimit strings, even if that stringcontains a quotation mark as a character.Do this: "Whats up, "Big Boy"?"Not this: Whats up, "Big Boy"?Use u, not U, for unicode escape sequences.Array literalsUse Array literals rather than new Array().Do this: []Not this: new Array()And this: [ 1, 2, 3 ]Not this: new Array(1, 2, 3)Use the Array constructor only to allocate an array of a prespecified size, as in new Array(3), which means [undefined, undefined, undefined ], not [ 3 ].Object literalsUse Object literals rather than new Object().Do this: {}Not this: new Object()And this: o = { a: 1, b: 2, c: 3 };Not this: o = new Object(); o.a = 1; o.b = 2; o.c = 3;Or this: o = {}; o.a = 1; o.b = 2; o.c = 3; Page 12/27
    • Function literalsAvoid using function literals to define anonymous functions; use a class method or package functioninstead.If you must use a function literal, declare a return type, and terminate the last statement inside the functionblock with a semicolon.Do this: function(i:int):void { doIt(i - 1); doIt(i + 1); }Not this: function(i:int) { doIt(i - 1); doIt(i + 1) }RegExp literalsUse the literal notation rather than constructing a RegExp instance from a String.Do this: var pattern:RegExp = /d+/g;Not this: var pattern:RegExp = new RegExp("d+", "g");XML and XMLList literalsUse the literal notation rather than constructing an XML instance from a String.Do this: var node:XML = <name first="Jane" last="Doe"/>;Not this: var node:XML = new XML("<name first="Jane" last="Doe"/>");Use double-quotes rather than single-quotes around XML attribute values:Do this: var node:XML = <name first="Jane" last="Doe"/>;Not this: var node:XML = <name first=Jane last=Doe/>;Class literalsUse a fully-qualified class literal only if necessary to disambiguate between two imported classes with thesame unqualified name.Do this: import mx.controls.Button; ... var b:Button = new Button();Not this: import mx.controls.Button; ... var b:Button = new mx.controls.Button();But here a fully-qualified name is required and therefore qppropriate: import mx.controls.Button; Page 13/27
    • import my.controls.Button; ... var b:Button = new mx.controls.Button();ParenthesesDont use unnecessary parentheses with common operators such as +, -, *, /, &&, ||, <, <=, >, >=, ==, and !=.Do this: var e:Number = a * b / (c + d);Not this: var e:Number = (a * b) / (c + d);And this: var e:Boolean = a && b || c == d;Not this: var e:Boolean = ((a && b) || (c == d));The precedence rules for other operators are harder to remember, so parentheses can be helpful with them.CoercionDont compare a Boolean value to true or false; it already is one or the other.Do this: if (flag)Not this: if (flag == true)Do this: var flag:Boolean = a && b;Not this: var flag:Boolean = (a && b) != false;Explicitly coerce an int, uint, Number or String to a Boolean:Do this: if (n != 0)Not this: if (n)And this: if (s != null && s != "")Not this: if (s)Let object references implicitly coerce to a Boolean:Do this: if (child)Not this: if (child != null)And this: if (!child)Not this: if (child == null) Page 14/27
    • Prefer the use of a cast to the use of the as operator. Use the as operator only if the coercion might fail andyou want the expression to evaluate to null instead of throwing an exception.Do this: IUIComponent(child).documentNot this: (child as IUIComponent).documentComparisonWrite comparisons in the order that they read most naturally:Do this: if (n == 3) // "if n is 3"Not this: if (3 == n) // "if 3 is n"++ and -- operatorsIn cases where the postfix and prefix forms are equivalent, use the postfix form. Use the prefix form onlywhen you need to use the value before it is incremented.Do this: for (var i:int = 0; i < n; i++)Not this: for (var i:int = 0; i < n; ++i)Ternary operatorUse a ternary operator in place of a simple if/else statement, especially for null checks:Do this: return item ? item.label : null;Not this: if (!item) return null; return item.label;But dont use nested ternary operators in place of complex if/else logic.Do this: if (a < b) return -1; else if (a > b) return 1; return 0;Not this: return a < b ? -1 : (a > b ? 1 : 0);new operatorUse parentheses after the class reference, even if the constructor takes no arguments. Page 15/27
    • Do this: var b:Button = new Button();Not this: var b:Button = new Button;StatementsTerminate each statement with a semicolon. Do not use the optional-semicolon feature of ActionScript 3.Do this: a = 1; b = 2; c = 3;Not this: a=1 b=2 c=3include statementsUse include, not the deprecated #include. Terminate the include statement with a semicolon, like any otherstatement.Do this: include "../core/ComponentVersion.as";Not this: #include "../core/ComponentVersion.as"Use relative, not absolute, paths.import statementsImport specific classes, interfaces, and package-level functions rather than using the * wildcard.Do this: import mx.controls.Button; import flash.utils.getTimer;Not this: import mx.core.*;use namespace statementsAvoid them; use :: syntax instead on each reference to something in a non-open namespace.Do this: import mx.core.mx_internal; // Later, in some method... mx_internal::doSomething();Not this: import mx.core.mx_internal; use namespace mx_internal; // Later, in some method... doSomething(); Page 16/27
    • if statementsIf the various branches of an if/else statement involve single statements, dont make them into blocks.Do this: if (flag) doThing1();Not this: if (flag) { doThing1(); }And this: if (flag) doThing1(); else doThing2():Not this: if (flag) { doThing1(); } else { doThing2(); }But if any branch has multiple statements, make all of them into blocks.Do this: if (flag) { doThing1(); } else { doThing2(); doThing3(); }Not this: if (flag) doThing1(); else { doThing2(); doThing3(); }When doing multiple error checks, use sequential if statements that test for failure and return early. Thesuccessful execution flow is then down the page, with the succesful return at the end of the method. Do notuse nested tests for success, which make the execution flow drift across the page. Page 17/27
    • Do this: if (!condition1) return false; ... if (!condition2) return false; ... if (!condition2) return false; ... return true;Not this: if (condition1) { ... if (condition2) { ... if (condition3) { ... return true; } } } return false;for statementsMake the body of a for loop be a block, even if it consists of only one statement.Do this: for (var i:int = 0; i < 3; i++) { doSomething(i); }Not this: for (var i:int = 0; i < 3; i++) doSomething(i);Store the upper limit for a for-loop variable in a local variable so that it isnt re-evaluated every time throughthe loop (unless, of course, it needs to be re-evaluated on each interation).Do this: var n:int = a.length; for (var i:int = 0; i < n; i++) { ... }Not this: for (var i:int = 0; i < a.length; i++) { Page 18/27
    • ... }Declare the loop var inside the parentheses of the for statement, unless it is reused elsewhere.Do this: for (var i:int = 0; i < 3; i++)Not this: var i:int; for (i = 0; i < 3; i++) { ... }while statementsMake the body of a while loop be a block, even if it consists of only one statement.Do this: while (i < n) { doSomething(i); }Not this: while (i < n) doSomething(i);do statementsMake the body of a do loop be a block, even if it consists of only one statement.Do this: do { doSomething(i); } while (i < n);Not this: do doSomething(i); while (i < n);switch statementsMake the body of each case clause, and of the default clause, be a block. Put the break or return statementwithin the block, not after it. If you are returning, dont put a break after the return. Treat the default clausesimilarly to the case clauses; break or return from it rather than falling through the bottom of the switch.Do this: switch (n) { case 0: { Page 19/27
    • foo(); break; } case 1: { bar(); return; } case 2: { baz(); return; } default: { blech(); break; } }Not this: switch (n) { case 0: foo(); break; case 1: { bar(); } break; case 2: baz(); return; break; default: blech(); } return statementsDo not enclose a return value in unnecessary parentheses.Do this: return n + 1;Not this: return (n + 1);Returning from the middle of a method is OK. Page 20/27
    • DeclarationsDont declare multiple constants or variables in a single declaration.Do this: var a:int = 1; var b:int = 2;Not this: var a:int = 1, b:int = 2;The override keywordIf present, put this first, before the access specifier.Do this: override protected method measure():voidNot this: protected override method measure():voidAccess specifiersPut an explicit access specifier everywhere that one is allowed. Do not use the fact that internal is theimplicit access specifier if none is written.Before making an API public or protected, think hard about whether it is really needs to be. Public andprotected APIs must be documented. They must also be supported for several releases before being formallydeprecated.The static keywordIf present, put this after the access specifier.Do this: public static const MOVE:String = &quot;move&quot;Not this: static public const MOVE:String = &quot;move&quot;;The final keywordIf present, put this after the access specifier.Do this: public final class BoxDirectionNot this: final public class BoxDirectionDeclare all “enum classes” to be final.Also declare “base” properties and methods (those starting with $) to be final.ConstantsAll constants should be static. There is no reason to use an instance constant, since all instances would storethe same value.Do this: Page 21/27
    • public static const ALL:String = "all";Not this: public const ALL:String = "all";ActionScript 3 does not allow a constant to have type Array or Object. Declare such constants using staticvar rather than static const, but put them in this section because they are conceptually constants.VariablesIf a variable needs to be initialized to a non-default value, do this in the declaration, not in the constructor.Do this: private var counter:int = 1;Not this: private var counter:int; ... public function MyClass() { super(); ... counter = 1; }Local variablesDeclare local variables at or just before the point of first use. Dont declare them all at the top of thefunction.Do this: private function f(i:int, j:int):int { var a:int = g(i - 1) + g(i + 1); var b:int = g(a - 1) + g(a + 1); var c:int = g(b - 1) + g(b + 1); return (a * b * c) / (a + b + c); }Not this: private function f(i:int, j:int):int { var a:int; var b:int; var c:int; a = g(i - 1) + g(i + 1); b = g(a - 1) + g(a + 1); c = g(b - 1) + g(b + 1); return (a * b * c) / (a + b + c); }Declare local variables only one per function. ActionScript 3 doesnt have block-scoped locals.Do this: Page 22/27
    • var a:int; if (flag) { a = 1; ... } else { a = 2; ... }Not this: if (flag) { var a:int = 1; ... } else { var a:int = 2; ... }And this: var i:int; for (i = 0; i < n; i++) { ... } for (i = 0; i < n; i++) { ... }Not this: for (var i:int = 0; i < n; i++) { ... } for (var i:int = 0; i &lt; n; i++) { ... }ClassesIf a class simply extends Object, omit the extends Object clause.The only “bare statements” in a class should be calls to static class initialization methods, such asloadResources(). Page 23/27
    • ConstructorsIf a classes has instance members, write a constructor, and make it explicitly call super(), even if it doesnothing else.If the constructor takes arguments that set instance vars, give the the same names as the instance vars.Do this: public function MyClass(foo:int, bar:int) { this.foo = foo; this.bar = bar; }Not this: public function MyClass(fooVal:int, barVal:int) { foo = fooVal; bar = barVal; }Dont set the classes instance vars in the constructor; do this in the declarations of the instance vars.However, if you need to reset the values of inherited instance vars, do this in the consturctor.Line widthWrap code to 100-character lines. This has the following advantages: • Developers with smaller screens dont have to scroll horizontally to read long lines. • A comparison utility can display two versions of a file side-by-side. • The font size can be increased for projection before a group without requiring scrolling. • The source code can be printed without clipping or wrapping. Page 24/27
    • ActionScript CommentsCreating ASDoc commentsA standard programing practice is to include comments in source code. The ASDoc tool recognizes aspecific type of comment in your source code and copies that comment to the generated output. The ASDoctool recognizes the following formatting and parsing rules for comments.Writing an ASDoc commentAn ASDoc comment consists of the text between the characters /** that mark the beginning of the ASDoccomment, and the characters */ that mark the end of it. The text in a comment can continue onto multiplelines.Use the following format for an ASDoc comment:/*** Main comment text.** @tag Tag text.*/As a best practice, prefix each line of an ASDoc comment with an asterisk (*) character, followed by asingle white space to make the comment more readable in the ActionScript or MXML file, and to ensurecorrect parsing of comments. When the ASDoc tool parses a comment, the leading asterisk and white spacecharacters on each line are discarded; blanks and tabs preceding the initial asterisk are also discarded.The ASDoc comment in the previous example creates a single-paragraph description in the output. To addadditional comment paragraphs, enclose each subsequent paragraph in HTML paragraph tags, <p></p>.You must close the <p> tag, in accordance with XHTML standards, as the following example shows:/*** First paragraph of a multiparagraph description.** <p>Second paragraph of the description.</p>*/All of the classes that ship with Flex contain the ASDoc comments that appear in the Adobe Flex LanguageReference. For example, view the mx.controls.Button class for examples of ASDoc comments.Placing ASDoc commentsPlace an ASDoc comment immediately before the declaration for a class, interface, constructor, method,property, or metadata tag that you want to document, as the following example shows for the myMethod()method:/*** This is the typical format of a simple* multiline (single paragraph) main description* for the myMethod() method, which is declared in Page 25/27
    • * the ActionScript code below.* Notice the leading asterisks and single white space* following each asterisk.*/public function myMethod(param1:String, param2:Number):Boolean {}The ASDoc tool ignores comments placed in the body of a method and recognizes only one comment perActionScript statement.A common mistake is to put an import statement between the ASDoc comment for a class and the classdeclaration. Because an ASDoc comment is associated with the next ActionScript statement in the file afterthe comment, this example associates the comment with the import statement, not the class declaration:/*** This is the class comment for the class MyClass.*/import flash.display.*; // MISTAKE - Do not to put import statement here.class MyClass {}Formatting ASDoc commentsThe main body of an ASDoc comment begins immediately after the starting characters, /**, and continuesuntil the tag section, as the following example shows:/*** Main comment text continues until the first @ tag.** @tag Tag text.*/The first sentence of the main description of the ASDoc comment should contain a concise but completedescription of the declared entity. The first sentence ends at the first period that is followed by a space, tab,or line terminator.ASDoc uses the first sentence to populate the summary table at the top of the HTML page for the class.Each type of class element (method, property, event, effect, and style) has a separate summary table in theASDoc output.The tag section begins with the first ASDoc tag in the comment, which is defined by the first @ characterthat begins a line, ignoring leading asterisks, white space, and the leading separator characters, /**. Themain description cannot continue after the tag section begins.The text following an ASDoc tag can span multiple lines. You can have any number of tags, where sometags can be repeated, such as the @param and @see tags, while others cannot.The following example shows an ASDoc comment that includes a main description and a tag section.Notice the use of white space and leading asterisks to make the comment more readable:/*** Typical format of a simple multiline comment.* This text describes the myMethod() method, which is declared below. Page 26/27
    • ** @param param1 Describe param1 here.* @param param2 Describe param2 here.** @return Describe return value here.** @see someOtherMethod*/public function myMethod(param1:String, param2:Number):Boolean {}For a complete list of the ASDoc tags, see ASDoc tags.Using the @private tagBy default, the ASDoc tool generates output for all public and protected elements in an ActionScript class,even if you omit the ASDoc comment. To make ASDoc ignore an element, insert an ASDoc comment thatcontains the @private tag anywhere in the comment. The ASDoc comment can contain additional textalong with the @private tag, which is also excluded from the output.ASDoc also generates output for all public classes in the list of input classes. You can specify to ignore anentire class by inserting an ASDoc comment that contains the @private tag before the class definition.The ASDoc comment can contain additional text along with the @private tag, which is also excludedfrom the output.Excluding an inherited elementBy default, the ASDoc tool copies information and a link for all ActionScript elements inherited by asubclass from a superclass. In some cases, a subclass may not support an inherited element. You can use the[Exclude] metadata tag to cause ASDoc to omit the inherited element from the list of inherited elements.The [Exclude] metadata tag has the following syntax:[Exclude(name="elementName", kind="property|method|event|style|effect")]For example, to exclude documentation on the click event in the MyButton subclass of the Button class,insert the following [Exclude] metadata tag in the MyButton.as file:[Exclude(name="click", kind="event")]Using HTML tagsYou must write the text of an ASDoc comment in XHTML-compliant HTML. You can use selected HTMLentities and HTML tags to define paragraphs, format text, create lists, and add anchors. For a list of thesupported HTML tags, see Summary of commonly used HTML elements.The following example comment contains HTML tags to format the output:/*** This is the typical format of a simple multiline comment* for the myMethod() method.* Page 27/27
    • * <p>This is the second paragraph of the main description* of the <code>myMethod</code> method.* Notice that you do not use the paragraph tag in the* first paragraph of the description.</p>** @param param1 Describe param1 here.* @param param2 Describe param2 here.** @return A value of <code>true</code> means this;* <code>false</code> means that.** @see someOtherMethod*/public function myMethod(param1:String, param2:Number):Boolean {}Using special charactersThe ASDoc tool might fail if your source files contain non-UTF-8 characters such as curly quotes. If it doesfail, the error messages it displays should refer to a line number in the interim XML file that was created forthat class. That can help you track down the location of the special character.ASDoc passes all HTML tags and tag entities in a comment to the output. Therefore, if you want to usespecial characters in a comment, you must enter them using HTML code equivalents. For example, to use aless-than (<) or greater-than (>) symbols in a comment, use &lt; and &gt;. To use the at-sign (@) in acomment, use &64;. Otherwise, these characters will be interpreted as literal HTML characters in theoutput.For a list of common HTML tags and their entity equivalents, see Summary of commonly used HTMLelements.Because asterisks (*) are used to delimit comments, ASDoc does not support asterisks within a comment.To use an asterisk in an ASDoc comment, you must use the double tilde (~~).Hiding text in ASDoc commentsThe ASDoc style sheet contains a class called hide, which you use to hide text in an ASDoc comment bysetting the class attribute to hide. Hidden text does not appear in the ASDoc HTML output, but doesappear in the generated HTML file so you should not use it for confidential information. The followingexample uses the hide class:/***Dispatched when the user presses the Button control.*If the <code>autoRepeat</code> property is <code>true</code>,*this event is dispatched repeatedly as long as the button stays down.**<span class="hide">This text is hidden.</span>*@eventType mx.events.FlexEvent.BUTTON_DOWN*/Rules for parsing ASDoc commentsThe following rules summarize how ASDoc processes an ActionScript file: Page 28/27
    • If an ASDoc comment precedes an ActionScript element, ASDoc copies the comment and codeelement to the output file.If an ActionScript element is not preceded by an ASDoc comment, ASDoc copies the code elementto the output file with an empty description.If an ASDoc comment contains the @private ASDoc tag, the associated ActionScript element andthe ASDoc comment are ignored.The comment text should always precede any @ tags, otherwise the comment text is interpreted asan argument to an @ tag. The only exception is the @private tag, which can appear anywhere inan ASDoc comment.HTML tags, such as <p></p>, and <ul></ul>, in ASDoc comments are passed through to theoutput.HTML tags must use XML style conventions, which means there must be a beginning and endingtag. For example, an <li> tag must always be closed by a </li> tag. Page 29/27
    • Organize ActionScript ClassesKeep ActionScript classes organized and arranged in a way that is consistent with the rest of the source codethroughout your application. This will help later when you or another developer needs to locate a particulararea of the code to make a quick change.Please use the following structure: Initial comment. (Author, version, copyright, code license, and so on) Package declaration Import statements Class-level metadata tags: Event, Style, Effect (with comments!) Class or interface implementation ASDoc comment Class or interface statement Static variables Public Protected Private Instance variables Public Protected Private Constructor Getter/setter methods (with backing variables) Methods, grouped according to functionality Page 30/27