You are on page 1of 28

AdobeFlex CodingGuidelines

MXML eActionScript3

AdobeFlexprogrammingcodingstyle&
guidelinesatDClick
v1.2 February/2007
FabioTerracini
fabio.terracini@dclick.com.br

1. Introduction .............................................................................................................3
2. Files.........................................................................................................................4
2.1. Filessuffixes .....................................................................................................4
2.2. Filenames.........................................................................................................4
2.3. Encoding...........................................................................................................4
3. ActionScript3.0.......................................................................................................5
3.1. Fileorganization ...............................................................................................5
3.2. Style..................................................................................................................6
3.2.1. Lineandlinewrap......................................................................................6
3.2.2. Declarations ...............................................................................................7
3.2.3. Curlybracesandparentheses......................................................................8
3.2.4. Statements..................................................................................................9
3.2.5. Spaces......................................................................................................13
3.3. Comments .......................................................................................................14
3.3.1. Documentationcomments ........................................................................14
3.3.2. Implementationcomment .........................................................................15
4. MXML ..................................................................................................................16
4.1. Fileorganization .............................................................................................16
4.2. Style................................................................................................................16
4.2.1. Lineandline ............................................................................................16
4.2.2. Nestlingcomponents ................................................................................17
4.2.3. Attributes .................................................................................................17
4.2.4. Script .......................................................................................................19
4.3. Comments .......................................................................................................19
4.3.1. Documentationcomments ........................................................................19
4.3.2. Implementationcomments .......................................................................19
5. Style ......................................................................................................................20
5.1. Generalrules ...................................................................................................20
6. Naming..................................................................................................................21
6.1. Generalrules ...................................................................................................21
6.2. Language........................................................................................................21
6.3. Packages .........................................................................................................21
6.4. Classes ............................................................................................................22
6.5. Interfaces........................................................................................................22
6.6. Methods ..........................................................................................................22
6.7. Variables.........................................................................................................23
6.8. Constants ........................................................................................................24
6.9. Namespaces ....................................................................................................24
7. GeneralPractices ...................................................................................................25
8. Appendix:ReservedWords ...................................................................................27
9. Documenthistory ..................................................................................................28

DClickDesenvolvimentodeSoftwareLtda.

1.Introduction
ThisdocumentaimstoestablishcodingguidelinestoapplicationwrittenwithAdobeFlex
2andActionScript3.
Establishacodingconventionmattersinthecontextthatthemostpartofthetimein
softwaredevelopmentlifecycleismaintenance.Thisway,helpingthecomprehension of
codepassagesisamust,consideringthatnotalwayswhosgoingtoperformthe
maintenanceisthesamepersonwhobuiltitinthefirsttime.Withacommonlanguage,
developerscanrapidlyunderstandotherpersonscode.Besides,theapplicationor
componentscodecanbedistributedorsoldtothirdparty.
Thepremisesofcodingconventionsare:
Consistency
Codecomprehension.
ThepracticesestablishedinthisdocumentarebasedonDClickworkway,Javacoding
conventionsandconventionsseen atAdobeFlex2SDK.

DClickDesenvolvimentodeSoftwareLtda.

2.Files
2.1. Filessuffixes
MXML code:.mxml
ActionScriptcode:.as
CSScode:.css

2.2. Filenames
Mustnotcontainspaces,punctuationsorspecialcharacters
ActionScript
o ClassesandInterfacesuseUpperCamelCase
o InterfacesalwaysstartwithanuppercaseI
IUpperCamelCase
o IncludesuselowerCamelCase
o Namespacedefinitionsuselower_case.
MXML
o AlwaysuseUpperCamelCase.
CSS
o AlwaysuselowerCamelCase.

2.3. Encoding
AllfilesmustbeinUTF8format.

DClickDesenvolvimentodeSoftwareLtda.

3.ActionScript3.0
3.1. Fileorganization
AnActionScriptfilemustcontainthefollowstructure:
#
1
2
3

Element
InitialComment
Packagedefinition
Namespacedeclaration
Ifhasone,itisthelastsection

Importstatements
1. Packageflash
2. Packagemx
3. Packagecom.adobe
4. Packagebr.com.dclick(DClickcomponents)
5. Packagesofthirdpartyinalphabeticalorder
6. Packageoftheprojectthisfilesbelongs
Usefullyqualifiedimports,i.e.,withouttheasterisk.Unless
whenabigpartofthepackageareused.
Prefer:importmx.core.Application
Avoid: importmx.core.*

5
6

7
8

usedeclarations (namespace)
Metadata
1. Event
2. Style
3. Effect
4. Othermetadatainalphabeticalorder.
Classorinterfacedefinition
staticvariables
1. public
a. const
b. Otherspublicstatic
2. internal
3. protected
4. private
5. custom namespaces
a. Inalphabeticalorder
Instancevariablesarenthandledbygettersandsetters
1. public
2. internal

DClickDesenvolvimentodeSoftwareLtda.

Obs.

Afilethatdefinesa
namespaceonly does
that.
Insidethesesections,
allimportsmustin
alphabeticalorder.
Iftheresa
namespaceimport,
thismustprecedethe
classimportsofthe
samepackage.

Inalphabeticalorder.

3. protected
4. private
6. custom namespaces
a. Inalphabeticalorder
10 Constructor
11 Gettersandsettermanagedvariablesandthegetandset
methodsthemselves,asrelatedvariables.Example:
privatevar_enabled:Boolean=true
privatevarenabledChanged:Boolean=false
publicfunctiongetenabled():Boolean
{
return_enabled
}

Seethevariables
sectiononthis
documentforrules
aboutvariables
managedby getand
setmethods.

publicfunctionsetenabled(value:Boolean):void
{
_enabled=value
enabledChanged=true
}

12 Methods

Groupedby
functionality,notby
scope.

3.2. Style
3.2.1.

Lineandlinewrap

When an expressiondoesntfitinonlyoneline,breakitinmorethanoneline.In these


casesthelinebreakmustfollowtheserules:

Breakitafteracomma
Breakitbeforeanoperator
Preferlinebreakathigherlevelcode
Alignthenewlineatthestartofthepreviousline
Ifthepreviousruleisntagoodoption,indentwithtwotabs.

Prefer:
//line#1:linebreakbeforetheimplementsoperator
//line#2:linebreakafteracomma
//lines#2and#3:indentedwithtwotabs
publicclassButtonextendsUIComponent
implementsIDataRenderer,IDropInListItemRenderer,
IFocusManagerComponent

DClickDesenvolvimentodeSoftwareLtda.

Avoid:
publicclassButtonextendsUIComponentimplements
IDataRenderer,IDropInListItemRenderer,
IFocusManagerComponent

Prefer:
//linebreakathigherlevel,occursoutsidetheparentheses
//linebreakdoesntbreakwhatisinsidetheparentheses
variable1=variable2+(variable3*variable4variable5)
variable6/variable7

Avoid:
//linebreaksplitstheparenthesescontentsintwolines
variable1=variable2+(variable3*variable4
variable5)variable6/variable7

Linebreakexamplewithternaryoperators:
b=(expression)?expression
:gamma
//aligned!
c=(expression)
?beta
:gamma

3.2.2.

Declarations

Doonlyonedeclarationperline:
Right:
vara:int=10
varb:int=20
varc:int=30

Wrong:
vara:int=10,b:int=20,c:int=30

Initializethevariableifpossible.Theresnoneedtoinitializethevariableifitsstartvalue
dependsonsomeprocesstooccur. Initializethevariableevenifitisthedefaultvalue.
Right:

DClickDesenvolvimentodeSoftwareLtda.

publicvarisAdmin:Boolean=false

Wrong:
publicvarisAdmin:Boolean//falseisdefaultforBoolean

Variablesdeclarationsshouldcomeonblockbeginning,exceptforvariablesusedin
loops.
publicfunctiongetMetadata():void
{
varvalue:int=123
//methodblockbeginning
...
if(condition)
{
varvalue:int=456
...
}

//ifblockbeginning

for(vari:int=0i<valori++)//inthefor
{
...
}
}

Dontdeclarevariableswithnamesthatwereusedbeforeinanotherblock,evenifwith
differentscope.

3.2.3.

Curlybracesandparentheses

Stylingrules:
Dontputaspacebetweenthemethodnameandtheopeningparentheses,and
dontputaspacebetweentheparenthesesandthemethodsarguments
Dontputaspacebetweentheobjectnameandhistype
Opencurlybracesinanewlineatthesamepositioninwhichthemethod
declarationbegins
Closecurlybracesinitsownlineatthesamepositioninwhichtheopencurly
braceis.
Methodsareseparatedbyanemptyline.
publicclassExampleextendsUIComponentimplementsIExample
{
privatevar_item:Object

DClickDesenvolvimentodeSoftwareLtda.

publicfunctionaddItem(item:Object):void
{
_item=item
...
}
publicfunctionanotherMethod():void
{
while(true)
{
...
}
}
}

3.2.4.

Statements

Simple
Simplestatementsmustbeoneperlineandshouldfinishwithasemicolon.
Right:
i++
resetModel()

Wrong:
i++resetModel()

Compound
Compoundstatements(theonesthatrequire{ and},like switch, if, while,etc) must
followtheserules:
Thecodeinsidethestatementmustbeindentedby onelevel
Thecurlybracemustbeinanewlineafterthedeclarationsbeginning,alignedat
thesameposition.Thecurlybracesareclosedinitsownline,atthepositionthe
curlybracethatopenedthestatement.
Curlybracesareusedinallstatements,evenifitsonlyasingleline.

Return

DClickDesenvolvimentodeSoftwareLtda.

Thereturn doesntneedstouseparenthesesunlessitraisestheunderstandability:
return
returngetFinalImage()
return(phase?phase:initPhase)

Conditionalif,elseif,else
if(condition)
{
simpleStatement
}

if(condition)
{
statements
}
else
{
statements
}
if(condition)
{
statements
}
elseif(condition)
{
statements
}
else
{
statements
}

Conditionalswitch,case
Switchstatementshavethefollowstyle:
switch(condition)
{
caseABC:
{
statements
//continue,withoutbreak
}

DClickDesenvolvimentodeSoftwareLtda.

10

caseDEF:
{
statements
break
}
caseJKL:
caseXYZ:
{
statements
break
}
default:
{
statements
break
}
}

Breakrules:
Alwaysusebreak in thedefault case.Normallyitsredundant,butitreinforces
theidea.
Ifacasedoesnthaveabreak,addacommentwherethebreakshouldbe.
Itsnotnecessarytouseabreak ifthestatementcontainsareturn.

Loopfor
for(initializationconditionupdate)
{
statements
}

for(initializationconditionupdate)

Loopfor..in
for(variterator:typeinsomeObject)
{
statements
}

Loopforeach..in
foreach(variterator:TypeinsomeObject)
{

DClickDesenvolvimentodeSoftwareLtda.

11

statements
}

Loopwhile
while(condition)
{
statements
}

Loopdo..while
do
{
statements
}
while(condition)

Errorhandlingtry..catch..finally
try
{
statements
}
catch(e:Type)
{
statements
}

Itcanhavethefinallystatement:
try
{
statements
}
catch(e:Type)
{
statements
}
finally
{
statements
}

With
with(this)
{
alpha=0.5

DClickDesenvolvimentodeSoftwareLtda.

12

3.2.5.

Spaces

Wrappinglines
Linebreaksmakesthecodeclearer,creatinglogicalgroups.
Usealinebreakwhen:

Betweenfunctions
Between themethodlocalvariablesanditsfirststatement
Beforeablock
Beforeasinglelinecommentorbeforeamultilinecommentaboutaspecific
codepassage
Between acodeslogicalsectiontomakeitclearer.

Blankspaces
Useblankspacestoseparateakeywordfrom itsparenthesesanddontuseaspaceto
separatethemethodnamefromitsparentheses.
while(true)
{
getSomething()
}

Ablankspacemustexistaftereverycommainanargumentslist:
addSomething(data1,data2,data3)

Allbinaryoperators(theoneswithtwooperands:+,,=,==,etc) mustbeseparatefrom
itsoperandsbyaspace.Dontuseaspacetoseparateunaryoperators (++,,etc).
a+=(5+b)/c
while(dasint<f)
{
i++
}

Ternaryoperatorsmustbeseparatedbyblankspacesandbrokeninmorethanonelineif
necessary:
a=(expression)?expression:expression

DClickDesenvolvimentodeSoftwareLtda.

13

Thefor expressionsmustbeseparatedbyblankspaces:
for(expr1expr2expr3)

3.3. Comments
3.3.1.

Documentationcomments

Documentationcommentsareforclasses,interfaces,variables,methodsandmetadata
withonecommentperelementbeforeitsdeclaration.Thedocumentationcommentis
meanttobereadandfullycomprehendedbysomeonethatwillusethecomponentbut
doesntnecessarily haveaccesstothesourcecode.
ThecommentformatisthesamereadbyASDoc,andthesyntaxdefinedinthe
document:http://labs.adobe.com/wiki/index.php/ASDoc:Creating_ASDoc_Comments
Example:
/**
*TheButtoncontrolisacommonlyusedrectangularbutton.
*Buttoncontrolslookliketheycanbepressed.
*
*@mxml
*
*<p>The<code>&ltmx:Button&gt</code>taginheritsallthe
* tagattributesofitssuperclass,andaddsthefollowing:</p>
*
*<pre>
*&ltmx:Button
*<b>Properties</b>
*autoRepeat="false|true"
*...
*<b>Styles</b>
*borderColor="0xAAB3B3"
*...
*/&gt
*</pre>
*
*@includeExampleexamples/ButtonExample.mxml
*/
publicclassButtonextendsUIComponent

Anotherexample:
/**
*@private
*Displaysoneoftheeightpossibleskins,
*creatingitifitdoesn'talreadyexist.
*/
mx_internalfunctionviewSkin():void
{

DClickDesenvolvimentodeSoftwareLtda.

14

3.3.2.

Implementationcomment

Animplementationcommenthastheintentiontodocumentspecificcodesectionsthatare
notevident.Thecommentsmustusethe// format,whethertheyaresingleormultiline.
Ifitsgoingtouseawholeline,itmustsucceedablanklineandprecedetherelatedcode:
//bailifwehavenocolumns
if(!visibleColumns||visibleColumns.length==0)

Thecommentcanbeinthesamecodelineifdoesntexceedthelinesmaximumsize:
colNum=0//visiblecolumnscompensateforfirstColoffset

Neverusecommenttotranslatecode:
colNum=0//setscolumnnumbersvariablestozero

DClickDesenvolvimentodeSoftwareLtda.

15

4.MXML
4.1. Fileorganization
AMXMLmustcontainthefollowstructure:
#
1

Element
XMLHeader:
<?xmlversion="1.0"encoding="UTF8"?>

Rootcomponent

Metadata
1. Event
2. Style
3. Effect
4. Othermetadatainalphabeticalorder
Styledefinitions

Scripts

6
7

Nonvisualcomponents
Visualcomponents

Obs.
Alwaysdeclarethe
encodingattheXML
header,andalwaysuse
UTF8.
Mustcontainall
namespacesusedinthe
file.

Preferexternalstyle
files.
UseonlyoneScript
block.

4.2. Style
4.2.1.

Lineandlinewrap

Useblanklinestomakecodeclearerbyvisuallygroupingcomponents.
Alwaysaddablanklinebetweentwocomponentsthatarechildren ofthesameparent
componentifatleastoneofthem(includingtheirchildren)usesmorethanoneline.
<mx:series>
<mx:ColumnSeriesyField="prev"displayName="Forecast">
<mx:stroke>
<mx:Strokecolor="0xB35A00"/>
</mx:stroke>

DClickDesenvolvimentodeSoftwareLtda.

16

<mx:fill>
<mx:LinearGradientangle="0">
<mx:entries>
<mx:GradientEntry.../>
<mx:GradientEntry.../>
</mx:entries>
</mx:LinearGradient>
</mx:fill>
</mx:ColumnSeries>
<comp:ColumnSeriesComponent/>
</mx:series>

I.e.,ifacomponenthasonly onechild,theresnoneedtoinsertablankline.Thebelow
LinearGradient containsonlyonechildentries.
<mx:LinearGradientangle="0">
<mx:entries>
<mx:GradientEntry.../>
<mx:GradientEntry.../>
</mx:entries>
</mx:LinearGradient>

Equally,astheentries childrenfitin oneline,theresnoblanklinebetweenthem.


<mx:entries>
<mx:GradientEntry.../>
<mx:GradientEntry.../>
</mx:entries>

4.2.2.

Nestlingcomponents

Children componentsmustbeindentedbytheirparentcomponent:
<mx:TabNavigator>
<mx:Container>
<mx:Button/>
</mx:Container>
</mx:TabNavigator>

4.2.3.

Attributes

Ordertheattributesby:
Property
o Thefirstpropertymustbetheid,if itexists
o Rememberthatwidth,height estyleName areproperty,notstyles.
Events

DClickDesenvolvimentodeSoftwareLtda.

17

Effects
Style
Ifexist,theid attributesmustbethefirstdeclared:
<mx:ViewStackid="mainModules"height="75%"width="75%">

Theattributesmustbeindentedbythecomponentsdeclarationifitusesmorethanone
line.
<mx:Label
width="100%"height="100%"truncateToFit="true"
text="Herecomesalongenoughtextthat..."/>

Indeclarationsthatusemorethanoneline,theonlyattributeinthefirstlineistheid.All
otherattributesmustbeinthenextlines,ordered.
<mx:ViewStackid="mainModules"
height="75%"width="75%"
paddingTop="10"paddingLeft="10"paddingRight="10">
<mx:ViewStack
height="75%"width="75%"
paddingTop="10"paddingLeft="10"paddingRight="10">

Relatedattributesshouldbeinthesameline.Inthefollowexample,thesecondlineonly
containsproperties,thethirdhasevents,fourthhasonlystylesandthelastonehasonly
effects.
<mx:Panel
title="VBoxContainerExample"status="Somestatus"
hide="doSomething()"creationComplete="doSomething()"
paddingTop="10"paddingLeft="10"paddingRight="10"
resizeEffect="Resize"/>

Incaseswheremorethanonelineisneededforanattributetype,usemorethanoneline
(observingconsistency,orderandlinesize)keepingthemgroupedbytype.Inthe
followingexample,thefirstlinecontainsthedeclarationplusid,secondhasonly
properties,thirdhasevents,fourthhassomestyles,fifthhaspaddingstyles(thereareno
effects).
<mx:Panelid="pnLoginInfo"
title="VBoxContainerExample"height="75%"width="75%"
resize="resizeHandler(event)"
titleStyleName="titleLogin"headerHeight="25"
paddingTop="10"paddingLeft="10"paddingRight="10"/>

DClickDesenvolvimentodeSoftwareLtda.

18

4.2.4.

Script

ThisisthestylefortheScript block:
<mx:Script>
<![CDATA[
code
]]>
</mx:Script>

4.3. Comments
4.3.1.

Documentationcomments

ASDoctooldoesntsupportdocumentationcommentsinMXMLfiles.Butdoingitis
encouragediftheMXMLfileisacomponentthatcouldbereused(andnotonlyasimple
view).Thisway,thefileshouldcontainanActionScriptalikecommentinsideaScript
block.

<mx:Script>
<![CDATA[
/**
*DocumentationcommentinsideaMXMLcomponent
*UsesthesameformatastheAScomment
*/
]]>
</mx:Script>

4.3.2.

Implementationcomments

Useimplementationcommentstodescribeinterfaceelementswhereitisntclearwhats
itspurposeorbehavior.
<!onlyshowsupifisinadminrole>

Ormultlinecomments:
<!
Multiplelinecomments...
...
...
>

DClickDesenvolvimentodeSoftwareLtda.

19

5.Style
5.1. Generalrules
Indentusingtabs.Thetabreferencesizeis4spaces,anditssuggested to
configuretheIDEthisway.
Codelinesmustnotexceed100characters1.

Using a1280pixelswideresolution(idealfor17displays)withEclipse,if70%widthisavailable to
code(and theother30%toNavigator), thelinehasabout103characterpositions.ThelimittoprintanA4
pageis80characters.

DClickDesenvolvimentodeSoftwareLtda.

20

6.Naming
6.1. Generalrules
Acronyms:avoidacronymsunlesstheabbreviationformismoreusualthanits
fullform(likeURL,HTML,etc). Projectnamescanbeacronymsifthisisthe
wayitscalled
OnlyASCIIcharacters,noaccents,spaces,punctuationsorspecialcharacters
DontusethenameofanativeFlexSDKcomponent(fromthemxpackagelike
Application,DataGrid,etc)neitherfromFlashPlayer(flashpackage,like
IOError,Bitmap,etc)
SincewritinginMXMLisaeasywaytowriteinActionScript,thenamingrules
inMXML arethesameasinActionScript(aMXMLfileislikeanActionScript
class,anditsinternalcomponentsandvariablesareproperties,forexample)
ThemainapplicationfileshouldbenamedMain.mxml
o NeveruseIndextoacomponentnamesinceitconflictswithASDoctool
generateddocs.

6.2. Language
Thecodeitselfmustbein English,exceptforverbsandnounsthatarepartof the
businessdomain(specificexpertiseareathesoftwareismeanttoaddress,i.e., thereal
worldpartthatisrelevanttothesystem).
Thisway,thefollowexamplesareacceptable:
DEFAULT_CATEGORIA
addNotaFiscal()
getProdutosByCategoria()
changeState()
UsuarioVO
screens/Reports.mxml

Thefollowexamples,although,arentvaliduses:
popularCombo()
mudarEstado()
UsuarioObjetoDeTransferencia

6.3. Packages

DClickDesenvolvimentodeSoftwareLtda.

21

Thepackagenamemustbewrittenin lowerCamelCase,startingwithsmallcapsand
otherinitialsinuppercase.
Thefirstelementinapackagenameisthefirstleveldomain(com,org,mil,edu,net,
gov)oratwolettercodeidentifyingacountryasdocumentedinISO3166followedby
thefirstleveldomain(br.com,ar.edu,uk.gov,etc).
Thenextelementisthecompany orclientthatownsthepackagefollowedbythe
projectsnameandmodule:
br.com.company.project.module

Examples:
br.com.dclick.mediaManager.uploadModule
com.apple.quicktime.v2

6.4. Classes
Classesnamesshouldprefernouns,butcanuseadjectivesaswell.Alwaysuse
UpperCamelCase.
Examples:
classLinearGradient
classDataTipRenderer

6.5. Interfaces
Interfacenamesmustfollowtheclassesnamingrules,withastartinguppercaseI.
Examples:
interfaceICollectionView
interfaceIStroke

6.6. Methods
Methods must start with a verb and are written in lowerCamelCase. If the method is
calledon an eventitshouldendwith Handler:

DClickDesenvolvimentodeSoftwareLtda.

22

Exemples:
makeRowsAndColumns()
getObjectsUnderPoint()
mouseDownHandler()

6.7. Variables
VariablesmustuselowerCamelCaseandobjectivelydescribewhattheyare.Variables
muststartwithandunderscore(_)iftheyaregoing tobemanipulatedby getandset
methods.
privatevar_enabled:Boolean=true
publicfunctiongetenabled():Boolean
{
return_enabled
}
publicfunctionsetenabled(value:Boolean):void
{
_enabled=value
}

Therearenovariableprefixes.ActionScripthastypedobjectandaclearandconcise
nameismoreimportantthantheobjectstype.Although,Booleanvariablesshouldstart
with can,is orhas.
privatevarisListeningForRender:Boolean=false
privatevarcanEditUsers:Boolean=true
privatevarhasAdminPrivileges:Boolean=false

Temporaryvariables(liketheonesusedinloopstatements)shouldbeonlyonecharacter.
Themostcommonlyusedarei,j,k,m,n,c,d. ThelowercaseLmustnotbeused.
for(vari:int=0i<10i++)

Thecatch variablesmustbee,nomatterwhatstheerrortype(ifithasaclass
describingit).
catch(e:Error)
{
hasFieldName=false
...
}

DClickDesenvolvimentodeSoftwareLtda.

23

6.8. Constants
Constantsmustbealluppercase,splittingthewordswithanunderscore(_):
publicstaticconstDEFAULT_MEASURED_WIDTH:Number=160
publicstaticconstAUTO:String="auto"

6.9. Namespaces
Namespacesnamesmustbealllowercase,splittingthewordwith anunderscore(_):
mx_internal
object_proxy

Thefilemusthavethesamenameasthenamespaceitdefines.

DClickDesenvolvimentodeSoftwareLtda.

24

7.GeneralPractices
UsethekeywordFIXMEinsidecomments(MXMLandActionScript)toflag
somethingthatsbrokenandshouldbefixed.UseTODOtoflagsomethingthat
worksbutcanbeimprovedbyarefactoring.Forthis,usetheFlexBuilder2Task
Plugin.
Assigntheiteratorvaluetoavariablebeforeusingitiftheperformance
improvementwillbesignificant(e.g.,insimplearraysitisntnecessary).
Right:
varmaxPhase:int=reallySlowMethod()
for(vari:Number=0i<maxPhasei++)
{
statements
}

Right:
varmonths:Array=['Jan','Fev','Mar']
//itsquickertocalculateanarraysize
//weretargetingreadabilitytoo
for(vari:Number=0i<months.lengthi++)
{
trace(months[i])
}

Wrong:
for(vari:Number=0i<reallySlowMethod()i++)
{
statements
}

Itsencouragedthecreationanduseof loosecoupledcomponents.Thelessa
componentknowsaboutanother,thegrateristhereusepossibilities.
InBooleanevaluations,placethefastestonesbefore.
Right:
if(isAdmin&&slowMethod(item))

Wrong:

DClickDesenvolvimentodeSoftwareLtda.

25

if(slowMethod(item)&&isAdmin)

Useconstantsifavailable.
Right:
myButton.addEventListener(MouseEvent.CLICK,myHandler)

Wrong:
myButton.addEventListener("click",myHandler)

Usespecifictypesifavailable.
Right:
privatefunctionmouseMoveHandler(event:MouseEvent):void

Wrong:
privatefunctionmouseMoveHandler(event:Event):void

Preferanonymousfunctionsforsimpleeventhandler,withonlyonestatement.
Thefollowstylesarepermitted.
myBytton.addEventListener(MouseEvent.CLICK,
function(event:MouseEvent):void
{
simpleStatement
}
)
myBytton.addEventListener
(
MouseEvent.CLICK,
function(event:MouseEvent):void
{
simpleStatement
}
)

DClickDesenvolvimentodeSoftwareLtda.

26

8.Appendix:ReservedWords
ThefollowtablecontainsActionScript3reservedwords:
as
class
delete
false
if
instanceof
native
private
super
to
use
with

break
const
do
finally
implements
interface
new
protected
switch
true
var

case
continue
else
for
import
internal
null
public
this
try
void

catch
default
extends
function
in
is
package
return
throw
typeof
while

Therearealsosyntactickeywordsthathavespecialmeansinsomecontextsso these
keywordsshouldbeavoidedonproducedcode:
each
include
override

get
dynamic
static

set
final

namespace
native

Andtherearefuturereservedwordsthatshouldbeavoidedtoo:
abstract
char
export
long
throws
virtual

boolean
debugger
float
prototype
to
volatile

byte
double
goto
short
transient

DClickDesenvolvimentodeSoftwareLtda.

cast
enum
intrinsic
synchronized
type

27

9.Documenthistory
Release1.2
FabioTerracini,February9,2007
Englishtranslationandsometyposfixed.
Release1.1
FabioTerracini,December13,2006
Detailedlinewrap(item3.2.1). Getandsetexamplesonvariables.Compound
statementsexample.Puntuactionsfixes.

Release1
FabioTerracini,December6,/2006
FirstreleasewithMXMLandActionscriptguidelines.Focuson standardizationand
readability.BasedonJavaguidelines,DClickinternalguidelinesandalsoonFlex2SDK.

DClickDesenvolvimentodeSoftwareLtda.

28

You might also like