`
uag
  • 浏览: 19344 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
最近访客 更多访客>>
社区版块
存档分类
最新评论

【转载】Flex SDK coding conventions and best practices

    博客分类:
  • flex
阅读更多

文章引自http://opensource.adobe.com/wiki/display/flexsdk/Coding+Conventions
有网友做了翻译,链接如下http://www.flashas.net/html/Flex/20080813/3579.html

有空翻译下

 

Flex SDK coding conventions and best practices

 

 

Introduction

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.

 


Naming

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.

Abbreviations

Avoid them as a general rule. For example, calculateOptimalValue() is a better method name than calcOptVal().

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:

  • 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 StringUtil

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.

Acronyms

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.

Word boundaries

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.

Type-specifying 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:

var button:Button = new Button();

Package names

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.

File names

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.

Namespace names

Start them with a lowercase letter and use underscores between words: mx_internal, object_proxy.

Interface names

Start them with I and use intercaps for subsequent words: IList, IFocusManager, IUID.

Class names

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.

Event names

Start them with a lowercase letter and use intercaps for subsequent words: "move", "creationComplete".

Style names

Start them with a lowercase letter and use intercaps for subsequent words: color, fontSize.

Enumerated values for String properties

Start them with a lowercase letter and use intercaps for subsequent words: "auto", "filesOnly",

Constant names

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:

public static const FOO_BAR:String = "fooBar";

Property (variable and getter/setter) names

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.

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 by implementing a property whose name is the base name with a $ prepended. This getter/setter should be marked finaland should do nothing more than call the supergetter/setter.

mx_internal final function get $numChildren():int
{
    return super.numChildren;
}

Storage variable names

Give the storage variable for the getter/setter foo the name _foo.

Method names

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.

mx_internal final function $addChild(child:DisplayObject):DisplayObject
{
    return super.addChild(child);
}

Event handler names

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().

Argument names

Use value for the argument of every setter:

Do this:

public function set label(value:String):void

Not this:

public function set label(lab:String):void

Or this:

public function set label(labelValue:String):void

Or this:

public function set label(val:String):void

Use event (not e, evt, or eventObj) for the argument of every event handler:

protected function mouseDownHandler(event:Event):void

Resource bundle names

If a resource bundle contains resources for a particular package, name the bundle the same as the package: controls, {formatters}}, validators.

Resource key names

Start them with a lowercase letter and use intercaps for subsequent words: pm, dayNamesShort.

Miscellaneous nomenclature

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.

Language Usage

This section discusses how we use the language constructs of ActionScript 3, especially when there are multiple ways to express the same thing.

Compilation options

Compile with the options -strict and -show-actionscript-warnings. (These are the defaults in the flex-config.xml file.)

Property-based APIs

Favor property-based APIs rather than method-based APIs, because these are more suitable for declarative-style MXML programming.

Type declarations

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:

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, and certainly not anObject 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 after Arrayindicate the type of the array elements. A future version of the language is likely to have typed arrays.

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

Literals

undefined

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.

int and uint literals

Do not use a decimal point in a integer.

Do this:

2

Not this:

2.

Use a lowercase x and uppercase A-Z in hexadecimal numbers.

Do this:

0xFEDCBA

Not this:

0Xfedcba  

Always 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 literals

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:

alphaFrom = 0.0;
alphaTo = 1.0;

Not this:

alphaFrom = 0;
alphaTo = 1;

However, don't do this for pixel coordinates, which are by convention integral even though they can in principle 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.0e12

Not this:

1.0E12

Use the default value NaN as the “not set” value for a Number.

String literals

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:

"What's up, \"Big Boy\"?"

Not this:

'What\'s up, "Big Boy"?'

Use \u, not \U, for unicode escape sequences.

Array literals

Use 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 literals

Use Object literals rather than new Object().

Do this:

{}

font-weight: normal; font-size: 11px; margin: 16

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics