You are on page 1of 48

Flex Best Practices

Sean Moore Sean the Flex guy Kannopy, Inc.


http://www.seantheflexguy.com http://www.actionscriptcheatsheet.com twitter: seantheflexguy http://www.kannopy.com

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.
Martin Fowler

Do you want to maintain this?


char x[]="((((((((((((((((((((((",w[]= "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b";char r[]={92,124,47},l[]={2,3,1 ,0};char*T[]={" |"," |","%\\|/%"," %%%",""};char d=1,p=40,o=40,k=0,*a,y,z,g= 1,G,X,**P=&T[4],f=0;unsigned int s=0;void u(int i){int n;printf( "\233;%uH\233L%c\233;%uH%c\233;%uH%s\23322;%uH@\23323;%uH \n",*x*w,r[d],*x+*w ,r[d],X,*P,p+=k,o);if(abs(p-x[21])>=w[21])exit(0);if(g!=G){struct itimerval t= {0,0,0,0};g+=((g<G)<<1)1;t.it_interval.tv_usec=t.it_value.tv_usec=72000/((g>> 3)+1);setitimer(0,&t,0);f&&printf("\e[10;%u]",g+24);}f&&putchar(7);s+=(9-w[21] )*((g>>3)+1);o=p;m(x);m(w);(n=rand())&255||-*w||++*w;if(!(**P&&P++||n&7936)){ while(abs((X=rand()%76)-*x+2)*w<6);++X;P=T;}(n=rand()&31)<3&&(d=n);!d&&--*x<= *w&&(++*x,++d)||d==2&&++*x+*w>79&&(--*x,--d);signal(i,u);}void e(){signal(14, SIG_IGN);printf("\e[0q\ecScore: %u\n",s);system("stty echo -cbreak");}int main (int C,char**V){atexit(e);(C<2||*V[1]!=113)&&(f=(C=*(int*)getenv("TERM"))==( int)0x756E696C||C==(int)0x6C696E75);srand(getpid());system("stty -echo cbreak" );h(0);u(14);for(;;)switch(getchar()){case 113:return 0;case 91:case 98:c(44,k =1);case 32:case 110:c(46,k=0);case 93:case 109:c(47,k=1);c(49,h(0));c(50,h(1 ));c(51,h(2));c(52,h(3));}}
Source: http://www0.us.ioccc.org/2001/ctk.c

Flex Best Practices articles

Flex best practices Part 1: Setting up your Flex project


http://www.adobe.com/devnet/flex/articles/best_practices_pt1.html

Flex best practices Part 2: Development practices


http://www.adobe.com/devnet/flex/articles/best_practices_pt2.html

Source of the standards


Based on extensive research into existing Flex, Flash, ActionScript, Java, C/C++ standards Reviewed/edited by prominent members of Flash/Flex community

Reviewed/edited by Adobe Flex Team

Planning

UML
Consider using UML to model application Start simple, dont go overboard Dont try to model the entire application Package ,Class, Interface diagrams Sequence diagrams *Component diagrams

Code Generation
Consider using code generation tools
(Round trip diagram to source code) (Generate diagrams from existing code)

Enterprise Architect, VASGen Cairngen

Application Development Frameworks


Framework
Cairngorm
PureMVC Mat Swiz

Application/Business logic
More Design Patterns
Facade

Strategy

Use frameworks for team-based development efforts Know when NOT to use a framework

Design Patterns
Consider using design patterns: Strategy Command Singleton MVC Decorator Faade Composite

Third Party APIs


Integrate third party libraries and APIs to save time Dont re-invent the ScrollBar! flexlib Degrafa Papervision Tweener

Final target platform[s]


Plan ahead for AIR deployment Offline mode Local DB Occasionally connected Prevent code conversion and refactoring later Thin Clients Linux

Workspaces

Use Workspaces to Stay Organized


Close old projects. Use separate/new workspaces.

Cluttered / Slow

Clean/Fast

Workspace/Project hierarchy
Workspace

C:\kannopy\flex\client\
Project

TwitterFlexClient
UpperCamelCase

Main Deployable MXML File

TwitterFlexClient.mxml

Setting up

Flex project output


Use the defaults (consistency across projects/organizations) Development: "bin-debug Deployment: "bin-release *Unless using local development server
define path during project creation process

Source code

Place Code Here

Standard used by other languages (Java, C)

Source Control
If not already: Use source control (SCM)
Track changes to codebase ALWAYS have a backup Critical in team environments Merge, difference, tag, branch, etc.

Source Control
Subversion, CVS, Perforce, GIT Subclipse for Flex Builder/Eclipse Dont include .project file or /settings directory (specific to each developers machine)

Managing SWC dependencies

Place SWCs Here

Use libs directory Reference shared SWC libraries using Flex Library path (under project properties)

Handling assets

File naming

File naming Donts


Do not use when naming files: spaces special characters acronyms or abbreviations periods

File naming standards


MXML files & Actionscript Class files

TwitterFlexClient
Uppercamel casing

Actionscript Interface Names

ILoggingTarget
Uppercamel casing , Begin file name with capital letter I

Coding standards

Use packages for code organization


Use the following format for package names: top level domain (TLD) application owners name project name logical grouping of related files

Use lowerCamelCase for package names

Packages
Dont use verbs, adjectives, adverbs for package names Name packages according to their classes: vo contains AccountVO, PhotoVO
package com.seantheflexguy.bestPracticesExample.vo {}

Classes
Append class types to the class name:
validators, formatters, events, and errors
com.seantheflexguy.burrow.validators.DateValidator

Append the skin type to the class name


com.seantheflexguy.burrow.skins.ExitButtonSkin

Append Base to superclass name


mx.charts.chartClasses.AxisBase

AS3 Class organization


Initial comment Package definition Imports Metadata
Event Style Effect

Class or interface definition

AS3 Class organization


Static variables Instance variables
public / public const internal protected private /private const

Constructor Getters/setter variables and methods Methods (grouped by functionality vs. scope)

Classes
Favor composition (HAS-A) over inheritance (IS-A )

Not a hard rule, use when appropriate

Interfaces
Defines contract for implementing classes Enables runtime polymorphism

Advantages: Classes can implement multiple interfaces Classes cannot extend multiple classes Leaves class open to extend another class

Interfaces
public interface ISearchService { function search( criteria:String ):void; }

public class SearchService implements ISearchService { public function search( criteria:String ):void { } }

Variables
Use meaningful and descriptive variable names:
private var tmpHoldr;

One variable declaration per line of source code:


var a = 1; var b = 2;

Always strongly type variables:

private var users:ArrayCollection;

Separate each variable declaration with a blank line Avoid the word object in identifiers: private var userObject;

Variables
Prefix Boolean variable names with can, is, or has
private var isAuthenticated:Boolean;

Capitalize constants:
DOMAIN, PORT, IP_ADDRESS

Prefix getter/setters with underscores and place the getter method above the setter method

Use fully qualified classpaths for event types


com.seantheflexguy.burrow.events.LoginEvent

Methods
Use meaningful and descriptive method names: private function doIt():void private function updateAfterEvent():void Use blank lines in between method definitions

Group methods in a class by functionality vs. scope (related functions)


Include a verb in method names: private function validateUser():void Use access modifiers for method definitions: private, public, internal, protected

Methods
Specify types for method arguments
parseResults( rawXMLData:XML ):ArrayCollection

Always provide return type even if it is void (returns nothing) or * (any type) Use blank spaces to separate keywords from parentheses
if (isAuthenticated) {}

Do not use spaces to separate method names from parentheses


getResults ():void

MXML
XML Header <?xml version="1.0" encoding="UTF8"?> Root component (w/ namespaces) Metadata
Event Style Effect

Style definitions (external css file) Scripts (only one Script block) Non visual components Visual components

MXML
Place the ID attribute as the first attribute for MXML elements

<mx:Button id=exitButton label=Exit/>


Group associated attributes together on one line

<mx:Button id=exitButton label=Exit labelPlacement=right paddingLeft="5" paddingRight="5/>

MXML
Indent nested MXML elements <mx:VBox> <mx:HBox> <mx:Label text=Search:/> <mx:TextInput id=searchText /> <mx:HBox> <mx:TextArea id=resultsText /> <mx:VBox>

CSS
- Comment styles - Group similar definitions - One declaration per line
/** * * Defines style information for the Exit * button control for the main UI. * */
.exitButton {
fillAlphas: 0.76, 0.52, 0.75, 0.65; fillColors: #009933, #009966, #00cc66, #009999; color: #ffffff; textRollOverColor: #ffffff; themeColor: #009966;

CSS
Avoid in-line CSS

<mx:Label text="1:30PM" width="90 color=#ccff00/>


Avoid naming class selectors based on appearance
Use lowerCamelCase for class selector names

.redButton { }

Use class selectors instead of type selectors when possible


.TitleWindow { }

ASDoc
/**
* * Use white space and leading asterisks increase comment readability * Do not use special characters in ASDoc comments (Hoses up ASDoc tool!) * */

<p></p> @ @private @return @see

- Use supported HTML to format the ASDoc output - Comment text should always precede any @ tags - Use @private for hiding classes from ASDoc - Use @return for methods with return types - Use @see for items that have relationships

Unit testing

Unit Testing
Use standard OOP best practices in test cases Encapsulation, inheritance, polymorphism, abstraction Document the test code

Use clear and concise test method names


Write simple test case methods

Apply the too simple to break rule for your unit tests Test complex methods and calculated properties not simple VO type classes

Books

Books
Programming Flex 3 Head First Design Patterns Pragmatic Programmer Beautiful Code Code Complete Programming Pearls Gang of Four (GOF) Design Patterns: Elements of Reusable ObjectOriented Software The Productive Programmer The Art of Interactive Design The Design of Everyday Things Dont Make Me Think

You might also like