Best Practices Coding v1.1

45
R i ve l lo Mu lti me d i a Co ns ulti ng Post Commen ts to: http://www.blog.rivello.org/?p=159  Best Practices for Co d ing Ac tionScrip t 3. 0 & MXML v1.1

Transcript of Best Practices Coding v1.1

Page 1: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 1/44

Rive llo Multimed ia Co nsulting

Post Comm ents to : http://www.blog.rivello.org/?p=159 

Best Prac tic es forCod ing Ac tionSc rip t 3.0 & MXML

v1.1

Page 2: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 2/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 2

1. Int roduc tio n .................................................................................................................. 4

2. Files ................................................................................................................................ 5

2.1. Files & File Suffixes ..................................................................................................... 5

2.2. File na mes.................................................................................................................. 5

2.3. Enc od ing ................................................................................................................... 5

3. Ac tionSc ript 3.0 ............................................................................................................ 6

3.1. File Organization ...................................................................................................... 6

3.2. Style .......................................................................................................................... 12

3.2.1. Line and Line Wrap ........................................................................................ 12

3.2.2. Dec larations .................................................................................................... 13

3.2.3. Curly Braces and Parentheses ..................................................................... 14

3.2.4. Sta tements ........................................................................................................... 15

3.2.5. Spaces .............................................................................................................. 20

3.3. Comments ............................................................................................................... 22

3.3.1. Docum enta tion Comments ......................................................................... 22

3.3.2. Implementa tion Comment ........................................................................... 224. MXML ........................................................................................................................... 24

4.1. File Organization .................................................................................................... 24

4.2. Style .......................................................................................................................... 25

4.2.1. Line and Line Wrap ........................................................................................ 25

4.2.2. Nesting Components ................................................................................... 26

4.2.3. Attributes .............................................................................................................. 26

4.2.4. Sc ript ..................................................................................................................... 27

4.3. Comments ........................................................................................................... 28

4.3.1. Docum enta tion Comments ........................................................................ 28

4.3.2. Implementa tion Comments .............................................................................. 285. Style ............................................................................................................................. 29

5.1. Gene ral Rules ...................................................................................................... 29

6. Naming .................................................................................................................... 30

6.1. Gene ral Rules ...................................................................................................... 30

6.2. Lang ua ge ............................................................................................................ 30

6.3. Packages............................................................................................................. 31

6.4. Classes ................................................................................................................. 31

6.5. Interfaces ............................................................................................................. 32

6.6. Metho ds ............................................................................................................... 32

6.7. Events ................................................................................................................... 32

6.8. Va riab les .............................................................................................................. 326.9. Constants............................................................................................................. 36

6.10. Namespaces ................................................................................................... 37

7. Gene ral Prac tic es .................................................................................................. 38

7.1 Fixme and Todo ....................................................................................................... 38

7.2 Casting ...................................................................................................................... 39

7.3 Typ ing to Interfaces ................................................................................................ 39

8. Append ix ................................................................................................................. 43

8.1 Reserved Words ....................................................................................................... 43

Page 3: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 3/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 3

8.2 Cha lleng es of Confo rming to Sta nd ards ............................................................ 43

9. Docum ent History .................................................................................................. 44

Page 4: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 4/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 4

1. INTRODUCTION

This doc ume nt a ims to estab lish c od ing guide lines to app lic a tions written with

Ad ob e Flex 3 and Ac tionSc rip t 3.

Estab lish a c od ing c onve ntion ma tters in this context be c ause the ma jority of

the time in the softwa re d evelopment life c ycle is spe nt doing ma intena nce.

Bec ause o f this, helping the c om prehe nsion of c od e p assages is a must,

c onsidering tha t the p erson w ho's go ing to p erform the m a intena nc e w ill not

a lwa ys be the same person w ho b uilt it in the first p lac e. With a c om mo n

langua ge , develope rs c an rap id ly understand other peo ple's cod e. Besides,

the a pp lica tion o r c om po nents c od e c an be d istributed or sold to third pa rties.

The prem ises of c od ing c onventions a re:

•  Consistency

•  Cod e c omp rehension

The p rac tices estab lished in this doc ument a re b ased on

Java c od ing c onventions and conventions seen a t Ad ob e Flex 3 SDK.

Page 5: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 5/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 5

2. FILES

2.1. Files & File Suffixes 

•  MXML c od e: .mxmlo  Best p rac tic e d ic ta tes that this should conta in m ostly MXML.

Ac tionSc rip t 3.0 is to be e xternalized to an Ac tionSc rip t 3.0 file.

•  Ac tionSc ript cod e: .as

o  ActionScript 3.0 Classes – Best practice dictates that this is most

co mmo n type o f file in any projec t.

o  ActionScript 3.0 Files – Best practice dictates that use of these files is to

be avoided . While a c om mon solution to externalize c od e from a n

MXML file, an Ac tionSc rip t 3.0 c lass is to be used instead .

•  CSS code: .css , .swf

o  Best p rac tice d icta tes to use .c ss for comp ile-time CSS and .swf fo r

run-time CSS. Run-t ime CSS offers more flexib ility in app lic a tion

development but requires mo re p rep ara tion. See Adob e Flex 3

Online Help for mo re information

(http :/ / lived oc s.adob e.co m/ flex/3/ html/he lp .html?c ontent=styles_10.

html).

2.2. File names

•  Must no t c onta in spac es, punc tuation m arks, or spe c ia l cha rac ters

•  Ac tionSc ripto  Classes and Inte rfaces use UpperCa me lCase

o  Interfac es a lwa ys sta rt w ith a n up per case I

  IUpperCamelCase

o  Inc ludes use low erCame lCa se

o  Nam espac e d efinitions use lower ca se.

•  MXML

o  Always use UpperCame lCa se.

•  CSS

o  Always use low erCame lCase.

2.3. Encoding

•  All files must b e in UTF8 forma t.

Page 6: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 6/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 6

3. ACTIONSCRIPT 3.0

3.1. File Organization 

An Ac tionSc ript c lass must conta in the following structure:

# Element Description

1 Initia l Comm ent

2 Pac kage definition

3 Namespa c e de claration

•  If it ha s one, it is the last sec tion

A file tha t d efines

a namespa ce only

does that.

4 Import statements

1. Package flash 

2.  Package mx 

3.  Package com.adobe 

4.  Packages of third party in alpha betica l order

5.  Pac kage o f the p rojec t this files belong s to

Use fully qualified imports, i.e., without the asterisk.

•  Prefer: imp ort mx.core.Applic ation; 

•  Avoid: impo rt mx.co re.*; 

Inside these sec tions

, all imp orts mustin alpha be tic al

order.

If there’s a

nam espa ce imp ort,

this must p rec ed e

the c lass imports of

the same pa ckage .

5 use de clarations (namespa c e) In alphab etica l

order.

6 Metadata

1.  Event

2.  Style

3.  Effect

4.  Other meta da ta in alphab etic al orde r.

7 Class or interfac e definition

8 Variables

1.  getter/setter

2.  public

a .  regular

b .  staticc .  constant

3.  private

a .  regular

b .  static

c .  constant

4.  protected

a .  regular

b .  static

Page 7: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 7/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 7

c .  constant

5.  c ustom name spa ces

6.  a . In alphabe tical order

9 Instanc e variab les a ren’ t hand led by gette rs and sette rs

1. public  

2. internal 

3. protected  

4. private  

6. c ustom na mespaces

a. In a lpha be tic al order

10  Constructor

11

 

Getters and sette r ma nage d va riab les and the get and set

methods themselves, as related variables. Example:

pub lic func tion ge t samp le () : String {

return _sample_str;

}

pub lic func tion set samp le (aVa lue : String) : vo id {

 _samp le_str = aVa lue;

}

p riva te va r _samp le_str : String;

See the va riab les

sec tion on this

do cument for rules

ab out va riab les

managed b y get

and set m ethod s.

Typ ically only three

lines are used fo rthe c omp lete

get ter/ set ter, unlike

example shown

here, which lacks

the m arg ins to d o

so.

12

 

Methods Grouped

by funct iona lity, not

by scope.

13 

Events

 // Event Dispa tc hers

private function d ispatc hSamp le () : void

{

 / / d ispa tc hEvent( new Event (Event.SAM PLE) );

}

 // Event Hand lers

Grouped first by‘event

d ispatc hers,’ then

by ‘event

handlers.’ Event

d ispatc hers a re

me thod s rea lly tha t

the c lass ca lls

inte rnally. This way

Page 8: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 8/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 8

private func tion onInit (aEvent : Event) : void

{

...

}

dispatchEvent is

not called

sporadically

throughout code ,

only in this sec tion

for ea sy readability.

Example: Temp late Class.as

//Marks the right margin of code

******************************************************************* 

 package com.company.templates

{

//-------------------------------------- 

// Imports 

//-------------------------------------- 

import flash.events.Event;

import flash.events.EventDispatcher;

//-------------------------------------- 

// Class 

//-------------------------------------- 

/** 

* This is the typical format of a simple multiline comment 

* such as for a <code>TemplateClass<code> class. 

*

* <p><u>REVISIONS</u>:<br> 

* <table width="500" cellpadding="0"> 

* <tr><th>Date</th><th>Author</th><th>Description</th></tr> 

* <tr><td>MM/DD/YYYY</td><td>AUTHOR</td><td>Class created.</td></tr> 

* <tr><td>MM/DD/YYYY</td><td>AUTHOR</td><td>DESCRIPTION.</td></tr> 

* </table> 

* </p> 

*

* @example Here is a code example.

* <listing version="3.0" > 

* //Code example goes here. 

* </listing> 

* <span class="hide">Any hidden comments go here.</span> 

*/ 

 public class TemplateClass extends EventDispatcher implements

ITemplateInterface{

//-------------------------------------- 

// Properties 

//-------------------------------------- 

//PUBLIC GETTER/SETTERS 

/** 

* This is the typical format of a simple comment for sample. 

*

*/ 

 public function get sample () : String { return _sample_str; }

Page 9: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 9/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 9

 public function set sample (aValue : String) : void {

 _sample_str = aValue;}

 private var _sample_str : String;

//PUBLIC CONST  

/** 

* Comment for <code>PUBLIC_STATIC_CONSTANT</code>. *

* @default PUBLIC_STATIC_CONSTANT

*/ 

 public static const PUBLIC_STATIC_CONSTANT : String =

"PUBLIC_STATIC_CONSTANT";

//PRIVATE  

/** 

* Comment for _sample2_str. 

*/ 

 private var _sample2_str : String;

//-------------------------------------- 

// Constructor  

//-------------------------------------- 

/** 

* This is the typical format of a simple multiline comment 

* such as for a <code>TemplateClass</code> constructor. 

* <span class="hide">Any hidden comments go here.</span> 

* @param param1 Describe param1 here. 

* @param param2 Describe param2 here. 

*/ 

 public function TemplateClass (){

//SUPER 

super ();

//VARIABLES 

var localSample_str : String =

TemplateClass.PUBLIC_STATIC_CONSTANT;

//PROPERTIES 

 _sample_str = TemplateClass.PUBLIC_STATIC_CONSTANT;

 _sample2_str = TemplateClass.PUBLIC_STATIC_CONSTANT;

//METHODS 

sampleMethod (_sample_str, _sample_str);

//EVENTS 

addEventListener (Event.INIT, onInit);

}

//-------------------------------------- 

// Methods 

Page 10: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 10/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 10

//--------------------------------------

//PUBLIC 

/** 

* This is the typical format of a simple multiline comment 

* such as for a <code>sampleMethod</code> method. 

* <span class="hide">Any hidden comments go here.</span> 

* * @param param1 Describe param1 here. 

* @param param2 Describe param2 here. 

*

* @return void 

*/ 

 public function sampleMethod (aArgument_str : String,

aArgument2_str : String) : void 

{

sampleMethod2 (aArgument_str, aArgument2_str);

}

//PRIVATE 

/** * This is the typical format of a simple multiline comment 

* such as for a <code>sampleMethod</code> method. 

* <span class="hide">Any hidden comments go here.</span> 

* @param param1 Describe param1 here. 

* @param param2 Describe param2 here. 

*

* @return void 

*/ 

 private function sampleMethod2 (aArgument_str : String,

aArgument2_str : String) : void 

{ dispatchSample ();

}

//-------------------------------------- 

// Events 

//--------------------------------------

//Event Dispatchers 

/** 

* Dispatches the Event.SAMPLE event. 

*/ 

[Event(name="SAMPLE", type="flash.events.Event")]

 private function dispatchSample () : void 

{//dispatchEvent ( new Event (Event.SAMPLE) );

}

//Event Handlers 

/** 

* Handles the Event.INIT event. 

*/ 

 private function onInit (aEvent : Event) : void 

{

Page 11: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 11/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 11

}

}

Page 12: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 12/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 12

3.2. Style

3.2.1. Line and Line Wrap

When a n expression doesn’ t fit on only one line (a s defined in sec tion 5,Style), break it on more than one line. In these c ases, the line brea k must

fo llow these rules:•  Brea k it a fter a c om ma

•  Brea k it before an op erator

•  Prefe r line b rea k at highe r leve l c od e

•  Align the new line a t the sta rt of the p revious line; if the p rev ious rule isn’ t

a go od op tion, indent with two ta bs.

Prefer: // line # 1: line b rea k before the impleme nts op erator

 // line # 2: line b rea k after a c omm a // lines # 2 and # 3: inde nted w ith two ta bs

public class Button extends UIComponent implements IDataRenderer,

IDropInListItemRenderer,

IFoc usMa nag erCom po nent

{

...

}

Page 13: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 13/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 13

Avoid:

public c lass Button extends UICo mp one nt imp lem ents

IData Renderer, IDrop InListItem Renderer,

IFoc usMa nag erCom po nent

{

...

}

Prefer:

 // line # 1 break a t higher leve l, oc c urs outside the pa rentheses

 // line # 2 break do esn’t brea k what is inside the parentheses

va riab le1 = variab le2 + (variable3 * variable4 va riable5)

- variable6 / va riable7;

Avoid :

 / / line # 1 break sp lits the pa rent heses c ontents in two lines

va riab le1 = va riab le2 + (variable3 * va riable4

- variable5) - variab le6 / variable7;

Line brea k examp le w ith terna ry op erato rs. Use only if too long to fit on one

line:

value = (very_long_name_for_an_expression) ? value2 

: value3; // a ligne d-left, ternary-unique!

3.2.2. Declarations

Do only one dec la ra tion p er line:

Right:

va r a_uint : int = 10;

va r b_uint : int = 20;

va r c_uint : int = 30;

Wrong:

Page 14: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 14/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 14

va r a_uint : int = 10, b_uint : int = 20, c_uint : int = 30;

Don’t initialize p ub lic and priva te va riab les in its dec la ra tion (exc ep t for

temporary va riab les and c onsta nts). Initia lize instead in the c onstructor of the

va riab le’s conta ining c lass. Initia lize the va riab le even if it is the d efa ult value.

Variab les d ec la ra tions should c om e on b loc k be ginning, excep t for variab les

used in loo ps.

pub lic function ge tMetad ata () : void

{

var value_uint : uint = 123; / / me thod -block b eg inning

}

pub lic function ge tMetad ata () : void

{

if (_c ond ition_boo lean) {

va r va lue_uint : uint = 456; // if-b lock beg inning

}

}

pub lic function ge tMetad ata () : void

{

  //for-block beginning

for (va r i : uint = 0; i < va lor; i++) {

...

}

}

Don’t dec la re va riab les with name s that were used before in another b loc k, even

if with different sc op e.

3.2.3. Curly Brac es and Parentheses

Styling rules:

•  Do put a spa c e be tween the method na me a nd the op ening parentheses.

•  Do put a spa c e betwee n the variab le ’s name and its type .

•  Do op en c urly brac es on the line b elow c lass dec la ra tions.

•  Do op en c urly brac es on the line below me thod dec la ra tions.

•  Do op en c urly brac es on the line b elow event d ec larations.

•  Do op en c urly braces on the same line in a ll other cases (if, fo r, while , do ,

Page 15: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 15/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 15

etc.).

•  Do c lose c urly braces in its ow n line a t the same position in which the op en

c urly b rac e is.

•  Do sep arate me thod s by an empty line.

•  Don’t put a spa c e b etween the p arentheses and the me thod’ s arguments.

pub lic c lass Examp le extend s UICo mp one nt imp leme nts IExample

{

private va r _item_ob ject : Ob ject;

pub lic func tion a dd Item (aX_uint : uint, aY_uint : uint) : void

{

if (true) {

...

} else {

...

}

for (va r i : uint = 0; I < = 10; i++ ) {

...

}

wh ile (true) {

...

}

}

}

3.2.4. Statements

Simple

Simp le sta tem ents must be o ne p er line a nd should end with a sem ico lon.

Right:

Page 16: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 16/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 16

i_uint++;

resetModel ();

Wrong:

i_uint ++; resetModel ();

Compound

Comp ound sta tements (the ones tha t typica lly use “ {“ and “ }” , like switch, if, while,

etc .) must fo llow these rules:

•  The c od e inside the state ment must be indente d by one level

•  The c urly brac e m ust be o n a new line a fter the de c la ra tion’ s beg inning,

a ligned a t the same position. The c urly b rac es a re c losed in its ow n line, a t

the same p osition a s the c urly brac e tha t op ened the sta teme nt.•  Curly braces are used in all sta tements, even if it’ s only a single line .

•  Alwa ys use the use “ {“ and “ }” even when optional 

Right:

if (isAvailable_boolean) {

...

}

Wrong:

if (isAvailable_boolean) ...

Return

The return doesn’ t need to use parentheses unless it ra ises the und erstandab ility:

return;

return getFinalIma ge ();

return (pha se ? p ha se : initPhase);

The return should occ ur only once in a method .

Conditiona ls with Simple Expressions

Page 17: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 17/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 17

if (c ond ition){

...

}

if (c ond ition) {

...

} else if (cond ition) {

...

} else {

...

}

Cond itiona ls with Compound Expressions

When the c ond itiona l expression is made o f multiple va riab les, use

parentheses and spac ing a s needed for rea dab ility.

 / / trea t m ultiple simp le expressions as just simp le expressions,

 // not spec ial formatting req uired

if (!c ond ition1 && c ond ition2){

...

}

 // use pa renthesis and spa c ing for com pound expressions

if (!co nd ition1 && (exp ression1 == exp ression 2) ){

...

}

Conditional switch, c aseSwitc h sta tem ents have the follow style:

Page 18: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 18/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 18

switch (condition ) {

case 1:

...

break; 

case 2:

...break; 

default:

...

break;

}

Brea k rules:

•  Always use break in the default case. Norma lly it’ s red undant, but it reinforce s

the idea .•  If a c ase d oesn’t ha ve a break, ad d a c omm ent where the break should b e.

Loop for

for (initialization; c ond ition; up da te) {

...

}

Loop for...in

for (var ite ra to r : Type in som eO bjec t) {

...

}

Loop for each...in

for each (var iterat or : Type in some Ob jec t) {

...

}

Loop while

Page 19: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 19/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 19

while (condition ) {

... 

}

Loop do...while

do {

... 

} while (condition );

Error handling try...catch...finally

try {

...

} ca tc h (a Error : Error) {

...}

It c an ha ve the finally sta tement:

try {

...

} ca tc h (a Error : Error) {

...

} finally {

...

}

Page 20: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 20/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 20

3.2.5. Spaces

Wrap ping lines

Line b rea ks ma ke the c od e c lea rer, c rea ting log ic al groups.

Use a line break:

•  Between a c od e’ s log ic a l sec tion to m ake it c lea rer

•  Between functions

•  Betw een the m etho d loc a l va riab les and its first sta tem ent

•  Before a b loc k

•  Before a single-line c om ment or be fore a multi-line c om ment about a

spec ific c od e p assage

Blank spac esUse b lank spac es to sep ara te a keyword from its parentheses and don’t use a spac e to sep arate the m ethod nam e from its pa rentheses.

while (true) {

ge tSom ething ();

}

A b lank spac e m ust exist a fter every com ma in an a rgume nts list:

ad dSome thing (da ta1, da ta2, da ta3);

All b ina ry op erato rs (the one s with two op erand s: +, - , =, ==, etc.) must

be sep arated from their op erand s by a spa ce . Don’t use a spac e to

separate unary operators (++, -- , etc .).

a += (5 + b) / c ;

while (d < MAX_COUNT) {

i++;

}

Ternary op erators must b e sep ara ted by b lank spaces and b roken on mo re tha n

one line if nec essary:

Page 21: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 21/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 21

a = (expression) ? e xpression : expression;

The  fo r expressions must b e sep arated by b lank spac es: 

for (expr1; expr2; exp r3) {

...

}

Page 22: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 22/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 22

3.3. Com ments

3.3.1. Doc umentation Comments

Doc ume nta tion c om me nts are fo r classes, interfac es, variab les, methods,

and meta da ta w ith one co mme nt per eleme nt before its de c laration.

The d oc umenta tion c omm ent is mea nt to b e read –and fully comp rehend ed – by

som eone w ho w ill use the c om ponent but d oesn’ t nec essarily have ac cess to

the source c od e.

The c om me nt forma t is the same rea d by ASDoc , and the syntax defined in

the do cument: http:/ / labs.adob e.co m/ wiki/ inde x.php/ ASDoc :Creating_ASDoc _C

omments.

Example:

 /** 

* This is the typ ica l forma t o f a simp le multiline c om me nt 

* such a s for a <c od e>sam pleMethod </c od e> method . 

* <spa n c lass="hide">Any hidd en c om ments go here.</span> 

* @pa ram pa ram 1 Desc ribe p a ram 1 here. 

* @pa ram pa ram 2 Desc ribe p a ram 2 here. 

*

* @return void  

*/  

public  function samp leMe thod (aA rgume nt_str : String ,

aArgume nt2_str : String) : void  

{

sampleMethod2 (aArgument_str, aArgument2_str);

}

3.3.2. Implem entation Comment

An imp leme ntation c om ment ha s the intention to do c umentspec ific c od e sec tions tha t a re no t evident. The c om me nts must use the  / /  format,

whe ther they a re single o r multiline.

If it’ s go ing to use a who le line, it must suc ceed a b lank line a nd p rec ed e

the related co de :

Page 23: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 23/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 23

 // ba il if we have no co lumns

if (!visibleColumns_a rray | | (visibleCo lumns_array.leng th == 0) ) {

...

}

The c om ment can be in the sam e c od e line if doesn’t exc eed the line’ s ma ximum

size:

c olumns_num = 0; / / visible c olumns c om pensate fo r offset

NEVERuse a c om ment to redund antly sta te wha t is ob vious in the c od e:

c olumns_num = 0; / / sets c olumn numb ers va riab les to zero

Page 24: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 24/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 24

4. MXML 

4.1. File Organization

MXML must c onta in the follow ing struc ture:

# Element Obs.

1 XML Hea der:

<?xml version=” 1.0” enc od ing=” UTF8”?>

Alwa ys dec la re the

enc od ing in the XML

heade r, and always

use UTF8.

2 Roo t c om ponent Must c onta in a ll

name spaces used in

the file.

3 Metadata

1. Event2. Style

3. Effec t

4. Other meta data in alphab etic al orde r

4 Style definitions Prefer externa l

style files.

5 Sc ripts Use only

one Sc rip t b loc k.

6 Non visual c om ponents

7 Visual c om ponents

Page 25: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 25/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 25

4.2. Style

4.2.1. Line and Line Wrap

Use b lank lines to m ake co de c lea rer by visua lly group ing c om ponents. Always

ad d a b lank line betwee n two c om po nents that a re c hildren of

the same pa rent c omponent if at lea st one of them (inc lud ing their c hild ren) uses

more tha n one line.

<mx:series>

<mx:Co lumnSeries yField=” prev” d isp layName =”Forec ast” >

<mx:stroke>

<mx:Stroke c olo r=”0xB35A00” / >

<mx:stroke>

<mx:fill>

<mx:LinearGradient ang le=”0”>

<mx:entries>

<mx:Grad ientEntry ... / >

<mx:Grad ientEntry ... / >

</ mx:entries>

</mx:LinearGradient>

</ mx:fill>

</ mx:Co lumnSeries>

<co mp :ColumnSeriesComp onent / >

</ mx:series>

I.e., if a c om pone nt has only one c hild , there’ s no need to insert

a b lank line. The below LinearGradient  c onta ins only one c hild entry.

<mx:Linea rGrad ient a ngle=” 0”>

<mx:entries>

<mx:Grad ientEntry ... / >

<mx:Grad ientEntry ... / >

</ mx:entries>

</mx:LinearGradient>

Equa lly, as the entries c hild ren fit on one line, there’s no b lank line b etween them .

Page 26: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 26/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 26

<mx:entries>

<mx:Grad ientEntry ... / >

<mx:Grad ientEntry ... / >

</ mx:ent ries>

4.2.2. Nesting Com ponents

Children c omp onents must b e indented by their pa rent c omp onent:

<mx:TabNaviga to r>

<mx:Container>

<mx:Butto n / >

</mx:Container>

</m x:TabNa vigato r>

4.2.3. Attributes

Orde r the a ttributes by:

•  Property

o  Do: The first p roperty must b e the id , if it exists;

o  Remember that width, height, and  styleName are prop erties,

not styles.

•  Events

•  Effects

•  Style

If e xist, the id a ttributes must be the first dec lared:

<mx:View Stac k id=” ma inMod ules” >

To a dd rea dab ility, it is prefe rred to p lac e one a ttribute per line, unless NONE of

the a ttributes a re likely to b e ed ited . In tha t case, one line is prefe rred . For a

likely to-be-ed ited a ttribute-set, use 1 line per a ttribute, a nd line-wrap the

c losing ta g

<mx:Label

id = “c ustom _lab el”

wid th = “ 100%”

height = “ 100%”

text = “ Here co mes a long enough text tha t... “

 / >

For an unlikely to-be -ed ited a ttribute-set , use one line, but o nly if the ent irety fits

Page 27: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 27/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 27

on one line.

Few a ttributes:

<mx:Lab el id = “ custom _label” w id th = “ 100%” / >

The a ttributes must b e indented by the c om ponent’s dec la ra tion if it usesmore tha n one line.

<mx:Label

id = “c ustom _lab el”

wid th = “ 100%”

 / >

4.2.4. Sc ript

In genera l cod ing, conventions d icta te tha t c od ing within MXML is ge nerally tobe avoided in favor of cod e-be hind te chniques. For excep tions, thoug h, this is

the style fo r the Sc rip t block of Ac tionSc ript 3.0 in the *.mxml file:

<mx:Sc rip t>

<![CDATA[

…]]>

</ mx:Sc rip t>

Page 28: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 28/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 28

4.3. Comments

4.3.1. Doc umentation Comments

ASDoc too l doesn’ t support doc umenta tion c om me nts in MXML files. But d oing

it is enc ourag ed if the MXML file is a c om ponent tha t c ould be reused (and not

only a simp le view ). This wa y, the file should c onta in an Ac tionSc ript c om ment

inside a Script  block.

<mx:Sc rip t>

<![CDATA[

 /**

• Docum entation co mme nt inside a MXML c omp onent

• Uses the sam e forma t as the AS c om ment

*/ 

]]></ mx:Sc rip t>

4.3.2. Implementation Com ments

Use imp lem enta tion co mm ents to d esc ribe interfac e e lem ents where

the ir purpose o r beha vior is unc lear.

<!— only shows up if is in admin role >

Or multiline c om ments:

<!Multiple

line comments...

...

...

>

Page 29: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 29/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 29

5. STYLE

5.1. General Rules

•  Indent using tabs. The ta b referenc e size is 4 spaces, and it’ s suggestedto configure the IDE this wa y.

•  Code lines must not exceed 100 characters 1.

1 Using a 1280 pixels-wide resolution (idea l for 17” d isp lays) w ith Ec lipse, if 70%

width is ava ilab le to c od e (and the other 30% to Naviga tor), the line has about

103 charac ter positions. The limit to p rint an A4 page is 80 charac ters.

Page 30: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 30/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 30

6. NAMING

6.1. General Rules

•  In gene ra l use the ‘ long ’ form of nam ing things. Code-com pletion (suchas intellisense) in cod e ed itors save you from having to retype the full

va riab le nam es in most cases. Time spent m anua lly typ ing these names

is neg ligible c om pared to time lost from c onfusion of less consistent

naming schem es whe re som etimes abbreviations are used and

som et imes they are not used . See ac ronym s* for excep tions to this rule.

•  *Ac ronyms: avo id ac ronyms unless the abbreviation fo rm is more usua l

tha n its full form (like URL, HTML, etc ). Projec t na mes c an be a c ronym s if

this is the way it’s c a lled .

•  Do use only ASCII cha rac ters and underscores.

•  Don’t use  accents, spac es, punc tua tion ma rks, or spec ia l cha rac ters.•  Don’t use the na me o f a na tive Flex SDK or Flash Playe r class na me for a

c ustom c lass name. It is perfec tly fine (ac tua lly, it's p refe rred ) to use

simila r nam es for ob jec ts (ex. va r bitmap : Bitma p = new Bitma p();).

•  Don’t use ‘ Index’ w ithin a c om ponent name since it conflic ts with ASDoc

tool generated doc s.

6.2. Language

The assumed aud ienc es of this doc ume nt a re tea ms who se prima ry spokenlanguage is Eng lish. Thusly, the code itself must be in Eng lish, excep t for verbs

and nouns that a re p art of the business domain (spec ific expertise a rea the

software is mea nt to address, i.e., the rea l-world part tha t is releva nt to the

system). In general use Eng lish for a ll parts of a ll cod ing and d oc umenta tion.

This convention is meant to standard ize the cod e.

Right:

DEFAULT_CATEGORIA

getProdutosByCategoria ();

c hang eState ();

Page 31: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 31/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 31

Wrong:

CATEOGRIA_POR_DEFECTO

ob tene rProd uc tosDeCa teg oría ();

mudarEstado ();

6.3. Packages

The p ac kag e na me must b e w ritten in lowerCamelCase, starting with small

caps and other initia ls in upper ca se.

The first elem ent in a packag e na me is the first level do main. Here is a

partia l list.

•  com

•  org

•  mil

•  edu

•  ne t

•  gov

The next element is the c om pa ny or client tha t ow ns the p ackage , follow ed

by the p roject’ s name and mod ule:

com.company.project.module

Examples:

import c om .adob e.effec ts.FullSc reenWipe; / / a fic titious referenc e

6.4. Classes

Class names should p refe rab ly be nouns, but c an use a d jec tives as well.

Always use UpperCamelCase .

Examples:

Page 32: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 32/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 32

class LinearGradient

c lass Data TipRenderer

6.5. Interfaces

Inte rfac e na mes must fo llow the c lass naming rules, with a sta rting

uppercase “ I” .

Examples:

interfac e ICo llec tionView

interfac e IStroke

6.6. Methods

Method s must sta rt w ith a verb a nd are w ritten in lowerCamelCase. If the

me thod is c a lled on a n event, it should end w ith Handler: 

Examples:

makeRowsAndColumns ();

getObjectsUnderPoint ();

6.7. Events

Events follow the same convention as me thod s; how eve r, they are to beg in

with ‘on.’  

Examples:

onMo useDow n ();

onSignUpC om p lete ();

6.8. Variables

The va riab le naming c onventions have be en develope d to help

deve lop ers know a t a g lance the most informa tion po ssib le from w ithin a c lass

(variab le type and va riab le scop e), and p rop erly hide deta ils from outside the

c lass. Overall va riab les must use lowerCamelCase and ob jec tively desc ribe

wha t they are. Most, by default, end with a suffix desc ribing the type of

Page 33: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 33/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 33

variab le for both na tive and custom type s. Here is a b rea kdown of various

variab le type s.

Private variables

Private va riab les must sta rt with an und erscore “ _” . This is to he lp

d istinguish them, which a ids the d eve lop er in being c onsc ious of the p riva te

va riab les vs. the p ub lic inte rface o f c lasses.

p riva te va r _samp le_str : String;

Native Variab le Suffixes

 _message_str

 _index_int

 _phoneNumber_uint

 _floatingCoordinant_num

Here is a p artia l list of suffixes. In general, use the full lower-c ased ,unabb reviated c lass name as the extension. There are excep tions due to leg ac y

Macromed ia c onventions.

Objec t type Variab le suffix

Array _array

Button _button

Boolean _boolean

Camera _camera

Color _color

Date _date

Error _error

Integer _int

LocalConnection_localconnection

Microphone _microphone

MovieClip _mc

PrintJob _pj

NetConnection _netconnection

NetStream _netstream

Numb er (Float) _num

Page 34: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 34/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 34

Shared Ob jec t _shared ob jec t

Sound _sound

String _str

TextField _textfield

TextArea _textarea

Text _text

Unsigned Inte ger _uint

Video _video

XML _xml

XMLNode _xmlnode

XMLSoc ket _xmlsocket

Custom variable suffixes

The sp irit o f the c onventions follow s here -- same c asing a nd same idea

of an extension to ind ica te typ e. If there is mo re tha n one va riab le o f the same

type in the same scop e, the type is used as the extension.

p rivate va r _topExterior_wind ow box : Windo wBox;

If there is NOT mo re tha n one va riab le o f the same type in the same

sc op e, the type c an be used as the va riab le name WITHOUT an extension. This

is not req uired , but is helpful to support the rea dability tha t the re is indeed only

one and o nly variab le o f its type.

p rivat e va r _ove rallInstanc eMa nage r : Ove rallInstanc eMa nag er;

Public variables

Public variables must not start with an und erscore “ _” and must not end  

with an extension. Avo id using pub lic va riab les in gene ra l, as it does not

prop erly enc apsula te the softw are d esign; instea d use g etter/sette r

conventions (see next sec tion). The p hilosop hy here is tha t ‘ inside ’ a c lass

(priva te variab les) the na ming is mo re verbose to inc lude a n extension tha t

deno tes the va riab le type. How eve r, from ‘outside’ a g iven c lass (pub lic

Page 35: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 35/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 35

me mb ers) should hide deta ils of imp lem enta tion inc lude va riab le typ e so no

extension is to b e used . This supports the O OD me thodolog y of enc apsulation,

pub lic va r samp le : String ;

Getter/Setters

Typ ica lly gette r/ set ters should occ upy only three lines, if margins a llow, in

the o rder show n below. In more c om plex situa tions, mo re tha n three lines ma y

be need ed , but tha t is the excep tion. The c onvention of ‘a Value’ is not

changed , not made more desc riptive, nor given a suffix. This keeps it short and

consistent ac ross a ll getter/ set te rs. Do not use a va riab le extension for the

pub lic interfac e. This prop erly hides the va riab le type from the API-user.

Implem enta tion deta ils such as tha t should not be shared by default. [Note :

This c od e samp le is left-aligned to fit within margins, in this doc ument . In your

cod e, indent ge tter/ sette rs as you wo uld any other code.]

pub lic func tion g et name () : String { return _name _str; }

pub lic func tion set name (aVa lue : String) : void { _name _str = aValue ;}

p riva te va r _na me_str : String ;

Boolean Variab les

Boo lean va riab les should sta rt w ith c an , is, or ha s .

private var isListeningForRender_boolean : Boolean = false;

p rivate va r canEd itUsers_boo lean : Boo lean = true;

p rivate va r hasAd minPrivileg es_boo lean : Boo lean = fa lse;

Tem porary Variab les

Tem porary variab les follow the same c onventions as privates, but without

the p refix “ _” .

va r sample_str : String ;

Tem porary Variab les in Loops

Tem porary va riab les (like the ones used in loop sta tements) should b eonly one c harac ter. The m ost c om mo nly used are i, j, k, m , n, c , d .

Page 36: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 36/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 36

for (var i : uint = 0; i < 10; i++) {

...

}

Arguments

Arguments, which are va riab les passed into a func tion, me thod , or

event, ac cessed from within that scop e, begin with ‘a ’

 //constructor

pub lic func tion Boo k (aTota lChapters_uint : Numb er = 0) : vo id {

...

}

  / /method

public function view Pag eByNumbe r (aPag e_uint : Numbe r = 1) : void {

...

}

  / /event

public function o nOp enNew Pag e (a CurrentPag e_uint : uint) : void {

...

}

6.9. Constants

Consta nts must be a ll upper case, sp litting the w ords with a n und erscore (_).

Constants a re no t g iven a suffix. Where a pp lica b le, a constant’ s va lue should

ma tc h the c onstant’s nam e. Constants a re exce ptiona l among va riables in

tha t they should b e initialized with a va lue in the dec lara tion.

Page 37: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 37/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 37

pub lic c onst DEFAULT_MEASURED_WIDTH : Number = 160;

pub lic sta tic const DEFAULT_MEASURED_WIDTH : Num ber = 160;

p riva te sta tic c onst AUTO : String = “ AUTO” ;

p riva te const AUTO : String = “ AUTO” ;

6.10. Namespa ces

Nam espaces name s must be a ll low er ca se, sp litting the wo rd with an

underscore (_):

mx_internal

object_proxy

The file m ust have the same name as the na me space it defines.

Page 38: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 38/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 38

7. GENERAL PRACTICES

7.1 Fixme a nd Todo

Use the keyword FIXME inside c om ments (MXML and Ac tionSc ript) to flag

som ething tha t’ s broken a nd should be fixed . Use TODO to flag som ething tha t

wo rks but c an be improved by a refa c toring. For this, use the Flex Builder Todo 

Plugin ava ilab le from a G oogle sea rch.

Assign the itera tor value to a va riab le b efore using it if the p erforma nce

improvem ent w ill be significant (e .g., in simp le a rrays, it isn’ t ne cessary).

Right:

va r maxPhase_uint : uint = rea llySlowMethod ();

for (var i : Numb er = -10; i < ma xPha se_uint; i ++) {

...

}

Right:

va r months_array : Array = [’ Jan’ ,’Fev’ ,’Ma r’ ];

 // it’s quicker to c alculate a n a rray size o utside a for

 // but w e’ re targeting read ab ility too

for (va r i : Number = 0; i < months_a rray.length; i++) {

...

}

Wrong:

for (va r i : Number = 0; i < rea llySlowMetho d (); i++) {

...

}

It’ s enc ouraged in the c rea tion and use o f loose c oup led com po nents.

The less a c om ponent knows about another, the g rea ter the reuse p ossibilities.

In Boo lean eva lua tions, place the fastest ones first.

Page 39: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 39/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 39

7.2 Casting

Ac tionSc rip t 3 supports not just c om pile-type type c hec king, but runtime

type c hec king a s we ll. If a c onflict exists with typ es during runtime in

Ac tionSc rip t 3, a runtime error will be thrown. In general, this is a goo d thing. Butit c an a lso require tha t you som etimes ma ssage your variab le typ ing to p revent

unwa rranted errors. This is c a lled ‘ c asting’ one va riab le o f a g iven typ e to

behave like it is of another type. There a re tw o ways to d o this. The ‘ as’

op erato r, new to Ac tionSc rip t 3.0, is the p referred tec hnique.

Avoid:

var gene ricInstanc e_ob jec t : Ob jec t = new Ob jec t ();

me thodTha tExpec tsAString ( String (ge nericInstanc e_ob jec t));

Prefer:

var gene ricInstanc e_ob jec t : Ob jec t = new Ob jec t ();

 // cast a s string to me et m ethod’ s signa ture

me thodTha tExpec tsAString ( gene ricInstanc e_ob jec t a s String );

 // to c all a String m ethod

(ge nericInsta nc e_ob jec t as String ).leng th; // retu rns the leng th

7.3 Typ ing to Interfac es

Typing va riab les a llow s the com piler to know wha t m em bers (variab les,

methods, events) are a va ilab le from its API.

•  You ha ve to list a ll pub lic m ethods tha t will be c om mo n for the c lasses

tha t imp lem ent this interfac e.

•  You d o so b y writing the me thod ’s signature, definition, name ,

parame ters, and return type .

•  You don't have to op en and c lose c urly brac es after the method

definition.•  You d on't have to (and can’t) spec ify if the me thod is p rivate , public , or

p rotec ted , bec ause a n interfac e is only for public scop e.

•  interfac e c an only extend other interfac es.

•  A c lass can imp lement m ore tha n one interfac e.

Com monly, a p rog ramm er ma y set the type of a va riab le to the va riable’ s

c lass.

Page 40: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 40/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 40

Example:

va r bigMo nste rSprite : BigMonste rSprite = new BigMonste rSprite ();

This works fine in many c ases, but using inte rfac es a llows many benefits.

An interfac e is a ‘promise’ from a c lass to the com piler about exac tly which o fits methods are a va ilab le from the API. When tw o o r more c lasses use the

same super c lass, it c an b e useful to trea t them the same (polymorphism) from

the API. How ever, if two c lasses do no t use the same super c lass and thus

cannot b e typ ed using a c lass, an interfac e is useful. See the examp le b elow.

Example:

 / / in IMonster.as interface file

package

{

pub lic interfac e IMonster {

function g etShot(dama ge _uint : uint) : void;

function g etCanShoo t() : Boo lean;

}

}

 / / in BigMonsterSprite.as c lass file

pub lic c lass BigMo nste rSp rite e xtends MovieClip imp leme nts IMonster

{

...

}

 / / in Sma llMonsterSprite.as class file

pub lic c lass Sma llMonsterSprite extend s Mo vieClip imp leme nts IMonster

{

...

}

Page 41: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 41/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 41

 / / in MonsterGam e.as class file

va r b igMonste rSprite : IMo nste r = new BigMo nste rSprite ();

va r sma llMo nste rSp rite : IMo nste r = new Sma llMonste rSprite ();

 // va riables type d as interfaces ‘ p rom ise’ a c ertain API so

 // the c om piler ag rees these state ments a re va lid

b igMonste rSp rite .ge tShot (10);sma llMo nste rSprite .ge tShot (20);

Page 42: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 42/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 42

Page 43: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 43/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 43

8. APPENDIX

8.1 Reserved Words

•  Ac tionSc ript 3 reserved wo rds are those w ords with spec ial meanings in thelanguage. Don’t use them for your ow n custom naming to avoid c onflic ts.

•  There a re a lso synta c tic keywo rds tha t have spec ial meanings in som e

contexts, so these keywords should be avoided on p rod uced cod e. 

•  There a re future reserved wo rds tha t should b e a voided , too.

8.2 Challenges of Conforming to Standards

See ing the va lue in standards and being vigilant to adhere to standards a re

two d ifferent things. Und isc iplined tea ms, time p ressures, and exhaustion cankeep p rojec ts from me eting goa ls of c od e standard iza tion. Bew are o f ‘Broken

Windows’ – a soc iolog ica l c onc ep t first p rop osed  by Jam es Q. Wilson and

George L. Kelling. If co de is not meet ing standards, the tend enc y is for

deve lop ers to ‘b rea k’ c onventions mo re a nd mo re, resulting in the slippery

slope to a non-standards-compliant project.

Here a re a few tips:

•  Sta rt Fresh – It is possible, but surely a c ha llenge , to convert an existing p rojec t to c onfo rm

to new standa rds. Co nsider wa iting to sta rt a new projec t to e stablish new c onventions.

• Use c od ing-file tem plates – c rea te gene ric or projec t-spe c ific tem plate s for com mon filetype s and use them to start each new file. Onc e you ha ve a standa rds do c (like this one ),

using temp late s is the mo st va luab le step to estab lish sta ndards.

•  Budg et time for stand ards-com pliant cod e – No a mo unt o f wishful thinking w ill help your

tea m me et stand ards if you d on’ t sched ule e noug h time . Sc hed ule 5-15% mo re time

during de velopme nt depe nding on how your tea m ad ap ts.

•  Sched ule c ode reviews – Undoub ted ly on any team , c od e-com plianc e d isc ipline will vary

and even the most ded ica ted de veloper will ma ke mistakes. In ad d ition to sc hed uling

cod e review s with the go a l of bug-free , well-optimized c od e, build in che c ks for standa rds

compliance.

o  Enc ourag e de velopers to c omm it only com pliant c od e.

o  Use regular expressions and othe r prog ram ma tic sea rch tec hniques to find

violat ions in com pliance.

  Sea rch fo r “ [ ^ ] \ :[ ^ ]” , for examp le, to find a ny violations of theconve ntion to keep spaces around c olons for instance (“ : “ ).

o  Setup a c hec klist for c od e review ers to follow . It may be a bo iled -dow n version of a

more c omp lete stand ards do c , for a q uick referenc e.

Page 44: Best Practices Coding v1.1

8/3/2019 Best Practices Coding v1.1

http://slidepdf.com/reader/full/best-practices-coding-v11 44/44

Best Prac tice s: Co d ing Rivello Multimed ia Co nsulting

Pag e 44

9. DOCUMENT HISTORY

•  Relea se 1.0

Samuel Asher Rivello, Ma rch 2008 

This is the first relea se with MXML and Ac tionsc ript guidelines. Focus

on standard iza tion and rea dab ility. This doc ume nt is based on the PDF

Ad ob e Flex Co d ing Sta ndards by Fab io Terrac ini. It is a lso informed b y

Java prog ramming guide lines, inte rna l guide lines, the Flex 3 SDK’s

guidelines, and personal experience and preference.

•  Relea se 1.1

Samuel Asher Rivello, July 2008 

The do c ha s been mod ified based on feed ba c k on rea dab ility,accuracy, and rob ustness.