分类:
2010-07-28 16:35:37
Note: This page is not yet complete and has some sections marked TBD. But there's plenty here to get you started!
This document lays out the coding standards for writing open-source Flex framework components in ActionScript 3. Adhering to these standards makes the source code look consistent, well-organized, and professional.
Some of these standards are completely arbitrary, since there is not always a “best way” to code. Nevertheless, in the interest of consistency, all commits to the Flex SDK project will be expected to follow these conventions.
Choosing good names is critical to creating code that is easy to use and easy to understand. You should always take the time to think about whether you have chosen the right name for something, especially if it is part of the public API.
Our naming standards are mostly consistent with those of ECMAScript and Flash Player 9.
Avoid 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 don't abbreviate, developers won't have to remember whether you shortened a word like “qualified” to “qual” or “qlfd”.
However, we have standardized on a few abbreviations:
This list probably does not include all abbreviations that are currently in use. If you're considering using an abbreviation that isn't listed here, please search the source code to determine whether it is already in use. If you don't 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 abbreviate them to H and V in the very-commonly-used container names HBox and VBox.
Various 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 that all-lowercase is used is when the acronym is used by itself as an identifier, or at the beginning of an identifier, and the identifier should start with a lowercase letter. See the rules below for which identifiers should start with which case.
Examples of identifiers with acronyms are CSSStyleDeclaration, IUID, uid, IIME, and imeMode.
When an identifier contains multiple words, we use two ways of indicating word boundaries: intercaps (as inLayoutManager or measuredWidth) and underscores (as in object_proxy). See the rules below for which method to use.
Sometimes it isn't clear whether a word combination has become its own single word, and we are unforunately 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 isn't actually in use) would be something like loadCSSURL(). But try to avoid such names.
If you want to incorporate the type into the name, make it the last “word”. Don't use the old ActionScript 1 convention of concatenating abbreviated type suffixes such as _mc to indicate type. For example, name a border Shape border,borderSkin, or borderShape, but not border_mc.
Often, the best name for an object is simply the same as its type, with different casing:
Start 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, or adverbs.
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.
For importable APIs, the file name must be the same as the public API inside. But include files don't have to follow this rule.
Start the names of include files for [Style(...)] metadata with an uppercase letter, use intercaps for subsequent 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.
Start them with a lowercase letter and use underscores between words: mx_internal, object_proxy.
Start them with I and use intercaps for subsequent words: IList, IFocusManager, IUID.
Start 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.
Start them with a lowercase letter and use intercaps for subsequent words: "move", "creationComplete".
Start them with a lowercase letter and use intercaps for subsequent words: color, fontSize.
Start them with a lowercase letter and use intercaps for subsequent words: "auto", "filesOnly",
Use 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:
Start 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.
Use p (for “property”) for a for-in loop variable:
If a class overrides a getter/setter and wants to continue to expose the base getter/setter, it should do so by implementing a property whose name is the base name with a $ prepended. This getter/setter should be marked final and should do nothing more than call the supergetter/setter.
Give the storage variable for the getter/setter foo the name _foo.
Start 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 be implemented as getter/setters instead. However, if getFooBar() is a slow method requiring a large amount of computation, 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 by implementing a method whose name is the base name with a $ prepended. This method should be marked final and should do nothing more than call the supermethod.
Event 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 the subcomponent name and an underscore: textInput_focusInHandler().
Use value for the argument of every setter:
Do this:
Not this:
Or this:
Or this:
Use event (not e, evt, or eventObj) for the argument of every event handler:
If a resource bundle contains resources for a particular package, name the bundle the same as the package: controls, {formatters}}, validators.
Start them with a lowercase letter and use intercaps for subsequent words: pm, dayNamesShort.
Avoid “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.
This section discusses how we use the language constructs of ActionScript 3, especially when there are multiple ways to express the same thing.
Compile with the options -strict and -show-actionscript-warnings. (These are the defaults in the flex-config.xml file.)
Favor property-based APIs rather than method-based APIs, because these are more suitable for declarative-style MXML programming.
Write a type annotation for every constant, variable, function argument, and function return value, even if the annotation is simply :* to indicate “no type”.
Do this:
Not this:
Use the narrowest type that is appropriate. For example, a loop index should be a int, not a Number, and certainly not an Object or *. As another example, a mouseDownHandler should declare its argument as event:MouseEvent, not event:Event.
Use int for integers, even if they can't 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 doesn't exist” value.
If you declare something to be of type Array, add a comment of the form /* of ElementType */ immediately afterArray indicate the type of the array elements. A future version of the language is likely to have typed arrays.
Do this:
Not this:
And this:
Not this:
Avoid 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.
Do not use a decimal point in a integer.
Do this:
Not this:
Use a lowercase x and uppercase A-Z in hexadecimal numbers.
Do this:
Not this:
Always write an RGB color as a six-digit hexadecimal number.
Do this:
Not this:
When dealing with indices, use the value -1 to mean “no index”.
If a Number value typically can be fractional, indicate this by using a decimal point, and follow the decimal point by a single trailing zero.
Do this:
Not this:
However, don't do this for pixel coordinates, which are by convention integral even though they can in principle be fractional.
Do this:
Not this:
Use e, not E, when using exponential notation.
Do this:
Not this:
Use the default value NaN as the “not set” value for a Number.
Use quotation marks (double quotes), not apostrophes (single quotes), to delimit strings, even if that string contains a quotation mark as a character.
Do this:
Not this:
Use \u, not \U, for unicode escape sequences.
Use Array literals rather than new Array().
Do this:
Not this:
And this:
Not this:
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 ].
Use Object literals rather than new Object().
Do this:
Not this:
And this:
Not this:
Or this:
Avoid using function literals to define anonymous functions; use a class method or package function instead.
If you must use a function literal, declare a return type, and terminate the last statement inside the function block with a semicolon.
Do this:
Not this:
Use the literal notation rather than constructing a RegExp instance from a String.
Do this:
Not this:
Use the literal notation rather than constructing an XML instance from a String.
Do this:
Not this:
Use double-quotes rather than single-quotes around XML attribute values:
Do this:
Not this:
Use a fully-qualified class literal only if necessary to disambiguate between two imported classes with the same unqualified name.
Do this:
Not this:
But here a fully-qualified name is required and therefore qppropriate:
Don't use unnecessary parentheses with common operators such as +, -, *, /, &&, ||, <, <=, >, >=, ==, and !=.
Do this:
Not this:
And this:
Not this:
The precedence rules for other operators are harder to remember, so parentheses can be helpful with them.
Don't compare a Boolean value to true or false; it already is one or the other.
Do this:
Not this:
Do this:
Not this:
Explicitly coerce an int, uint, Number or String to a Boolean:
Do this:
Not this:
And this:
Not this:
Let object references implicitly coerce to a Boolean:
Do this:
Not this:
And this:
Not this:
Prefer the use of a cast to the use of the as operator. Use the as operator only if the coercion might fail and you want the expression to evaluate to null instead of throwing an exception.
Do this:
Not this:
Write comparisons in the order that they read most naturally:
Do this:
Not this:
In cases where the postfix and prefix forms are equivalent, use the postfix form. Use the prefix form only when you need to use the value before it is incremented.
Do this:
Not this:
Use a ternary operator in place of a simple if/else statement, especially for null checks:
Do this:
Not this:
But don't use nested ternary operators in place of complex if/else logic.
Do this:
Not this:
Use parentheses after the class reference, even if the constructor takes no arguments.
Do this:
Not this:
Terminate each statement with a semicolon. Do not use the optional-semicolon feature of ActionScript 3.
Do this:
Not this:
Use include, not the deprecated #include. Terminate the include statement with a semicolon, like any other statement.
Do this:
Not this:
Use relative, not absolute, paths.
Import specific classes, interfaces, and package-level functions rather than using the * wildcard.
Do this:
Not this:
Avoid them; use :: syntax instead on each reference to something in a non-open namespace.
Do this:
Not this:
If the various branches of an if/else statement involve single statements, don't make them into blocks.
Do this:
Not this:
And this:
Not this:
But if any branch has multiple statements, make all of them into blocks.
Do this:'
Not this:
When doing multiple error checks, use sequential if statements that test for failure and return early. The successful execution flow is then down the page, with the succesful return at the end of the method. Do not use nested tests for success, which make the execution flow drift across the page.
Do this:
Not this:
Make the body of a for loop be a block, even if it consists of only one statement.
Do this:
Not this:
Store the upper limit for a for-loop variable in a local variable so that it isn't re-evaluated every time through the loop (unless, of course, it needs to be re-evaluated on each interation).
Do this:
Not this:
Declare the loop var inside the parentheses of the for statement, unless it is reused elsewhere.
Do this:
Not this:
Make the body of a while loop be a block, even if it consists of only one statement.
Do this:
Not this:
Make the body of a do loop be a block, even if it consists of only one statement.
Do this:
Not this:
Make the body of each case clause, and of the default clause, be a block. Put the break or return statement within the block, not after it. If you are returning, don't put a break after the return. Treat the default clause similarly to the case clauses; break or return from it rather than falling through the bottom of the switch.
Do this:
Not this:
Do not enclose a return value in unnecessary parentheses.
Do this:
Not this:
Returning from the middle of a method is OK.
Don't declare multiple constants or variables in a single declaration.
Do this:
Not this:
If present, put this first, before the access specifier.
Do this:
Not this:
Put an explicit access specifier everywhere that one is allowed. Do not use the fact that internal is the implicit access specifier if none is written.
Before making an API public or protected, think hard about whether it is really needs to be. Public and protected APIs must be documented. They must also be supported for several releases before being formally deprecated.
If present, put this after the access specifier.
Do this:
Not this:
If present, put this after the access specifier.
Do this:
Not this:
Declare all “enum classes” to be final.
Also declare “base” properties and methods (those starting with $) to be final.
All constants should be static. There is no reason to use an instance constant, since all instances would store the same value.
Do this:
Not this:
If a variable needs to be initialized to a non-default value, do this in the declaration, not in the constructor.
Do this:
Not this:
Declare local variables at or just before the point of first use. Don't declare them all at the top of the function.
Do this:
Not this:
Declare local variables only one per function. ActionScript 3 doesn't have block-scoped locals.
Do this:
Not this:
And this:
Not this:
If 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 as loadResources().
If a classes has instance members, write a constructor, and make it explicitly call super(), even if it does nothing else.
If the constructor takes arguments that set instance vars, give the the same names as the instance vars.
Do this:
Not this:
Don't 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.
TBD
TBD
TBD
TBD
One public API (usually a class, sometimes a namespace or function) inside the package statement.
Helper classes
bare statements
This section presents the order in which a Flex framework file should be organized.
Include a copyright notice at the top of every .as file in the framework. The format for the 2008 open-source copyright is given below.
Note that it is 80 characters wide.
TBD
TBD
TBD
Organize the class metadata into sections, in the order Events, Styles, Effects, Excluded APIs, and Other Metadata.
Put a minor section header before each section. Note that the minor section headers are 40 characters wide and that there are two spaces between the // and the section name.
Alphabetize the metadata by name="..." within each section. In the Other Metadata section, alphabetize them by metadata tag name.
TBD
Every class should include core/Version.as using a relative path. This file contains the declaration for static const VERSION:String.
TBD
TBD
Put static const declarations here.
ActionScript 3 does not allow a constant to have type Array or Object. Declare such constants using static varrather than static const, but put them in this section because they are conceptually constants.
Declare any static variables of type Function that get mixed in rather than being declared as methods.
TBD
TBD
Declare static getters and setters here. Order them alphabetically by property name. Use a minor separator with the property name for each one. Put the getter before the setter.
Put static function declarations here.
TBD
TBD
Put overrides of non-static getters and setters here. Order them alphabetically by property name. Use a minor separator with the property name for each one. Put the getter before the setter.
Put new non-static getters and setters here. Order them alphabetically by property name. Use a minor separator with the property name for each one. Put the getter before the setter.
Put overrides of non-static functions here.
Put new non-static functions here.
Put overrides of event handlers here.
Put new event handlers here.
TBD
This section covers how a Flex framework class should be formatted.
Wrap code to 80-character lines. This has the following advantages:
Use 4-space indentation. Configure your text editor to insert spaces rather than tabs. This allows another program that uses a different indentation setting, such as Notepad with its 8-character indents, to display the code without disfiguring it.
The major section separators inside a class look like this:
They extend from column 4 through column 80. The text is indented to column 8.
The minor section separators inside a class, such as between properties, look like this:
They extend from column 4 through column 40. The text is indented to column 8.
Put a single blank line above and below the separators.
Use a single blank line as a vertical separator between constant, variable, or function declarations.
TBD
Do this:
Not this:
Don't put any spaces before or after the left bracket or before the right bracket.
Do this:
Not this:
Follow a comma with a single space. This applies to argument lists, array literals, and object literals.
Put a single space after the left bracket and a single space before the right bracket, and put a single space after (but none before) each comma.
Do this:
Not these:
An empty array is a special case.
Do this:
Not this:
Format lengthy array initializers requiring multiple lines with aligned brackets:
Put a single space after the left brace and a single space before the right brace, and put a single space after the colon separating the property name and value.
Do this:
Not these:
An empty Object is a special case.
Do this:
Not this:
Format lengthy object initializers requiring multiple lines with aligned braces:
TBD
Don't put any spaces before or after the colon that separates a variable, parameter, or function from its type.
Do this:
Not these:
And this:
Not these:
Put a single space around the assignment operator.
Do this:
Not this:
Put a single space around infix operators.
Do this:
Not this:
Put a single space around comparison operators.
Do this:
Not this:
Don't put any spaces between a prefix operator and its operand.
Do this:
Not this:
Don't put any spaces between a postfix operator and its operand.
Do this:
Not this:
Start each statement on a new line, so that you can set a breakpoint on any statement.
Do this:
Not this:
Align the braces of statement blocks.
Do this:
Not this:
TBD
TBD
Do this:
''Not these:''
If the parameters have to wrap, indent the subsequent lines after the left parenthesis. Put multiple parameters per line if they fit. Otherwise, put one per line. If even one won't fit, put the first one on the second line, indented past the beginning of the function name.
TBD
Do this:
Not these:
Follow the if keywords with a single space before the left parenthesis. Don't put any spaces after the left parenthesis or before the right parenthesis.
Do this:
Not these:
else if ?
multiline ?
Follow the for keyword with a single space before the left parenthesis. Don't put any spaces after the left parenthesis or before the right parenthesis.
Do this:
Not these:
If the for clause needs to wrap, indent the subsequent lines after the left parenthesis.
Follow the switch keyword with a single space before the left parenthesis. Don't put any spaces after the left parenthesis or before the right parenthesis.
Do this:
Not these:
Follow the switch keyword with a single space before the left parenthesis. Don't put any spaces after the left parenthesis or before the right parenthesis.
Do this:
Not these:
braces are always balanced
no braces around single lines
single statement per line
Only document the first function of a get/set function pair for a property. The idiom for defining and documenting a property is:
Also, ASDoc comments are applied to metadata tags as well as other constructs within a class so take care that your comments apply to the proper target. If you tag a property as Bindable, your property comment must precede the get function, not the Bindable metadata tag.
Do this:
Not this: