Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ActionScript 2.0 2006

.pdf
Скачиваний:
101
Добавлен:
17.08.2013
Размер:
12.47 Mб
Скачать

Chapter 5

An alternative is to use a separator, such as an underscore, between words. The camelBack syntax allows English-like variable names to be used and easily read without the addition of separators, which take up more screen space.

Variable names should be descriptive, but should not be sentences. Use the shortest name that is still meaningful.

The only time a variable name should consist of only one letter is when it’s used as an iterator within a for loop. The convention is to use the letters i through n as iterators, starting at i and using subsequent letters as loops are nested inside of each other. Here’s an example in which the variable j is in a for loop nested in a for loop that includes the variable i:

for (var i=0; i < someNum; i+)

{

// Outer loop

for (var j=0; j < someDifferentNum; j++)

{

//Inner loop

}

}

Making Boolean Variables into Questions

Boolean variable names should be written in such a way that it is immediately obvious what true and false signify. One approach is to write the variable name in the form of a question, usually starting with the word is. Here are some examples:

var isFirstPass:Boolean; var isDone:Boolean;

var isOpen:Boolean;

var isPendingApproval:Boolean;

The names should always be phrased as a positive statement. The following should not be used:

var isNotDone:Boolean = false; var isNotApproved:Boolean = true; var isNotOpen:Boolean = true;

They would be better written as:

var isDone:Boolean = true;

var isApproved:Boolean = false;

var isClosed:Boolean = true; // or var isOpen:Boolean = false;

Avoiding Reserved Words

ActionScript reserves a number of words for its own use, and you must avoid using them in your code. Two main groups of reserved words exist: keywords (core statements) and words that are reserved for future use. The compiler usually spits out an error and stops the compilation when a reserved keyword

108

Getting Started with Coding

is used for a variable name. Variables named the same as common methods or properties still work, but they may obscure access to the method or the property. The rule of thumb is that when the Macromedia Flash editor highlights a variable name in blue, there is a reserved keyword or a built-in method or property with the same name, and you should change your variable’s name.

Following is a list of reserved keywords:

Reserved Keywords

add

Extends

interface

set

and

finally

intrinsic

static

break

for

le

switch

case

function

lt

tellTarget

catch

ge

ne

this

class

get

new

throw

continue

gt

not

try

default

if

on

typeof

delete

ifFrameLoaded

onClipEvent

var

do

implements

or

void

dynamic

import

private

while

else

in

public

width

eq

instanceof

return

 

 

 

 

 

Here are the keywords that ActionScript has reserved for future use:

Keywords Reserved for Future Use

abstract

double

goto

synchronized

byte

enum

long

throws

char

export

protected

transient

debugger

float

short

volatile

There is also a list of class names and component names that should not be used for variable names. Though the compiler is case sensitive and allows a variable name such as object or string, it is bad practice to have a variable name that differs from a keyword only by case. Here’s the list:

109

Chapter 5

Reserved Class and Component Names

Accessibility

Date

Microphone

StyleManager

Accordion

DateChooser

Mouse

System

Alert

DateField

MovieClip

TextArea

Array

Delta

MovieClipLoader

TextFormat

Binding

DeltaItem

NetConnection

TextInput

Boolean

DeltaPacket

NetStream

TextSnapshot

Button

DepthManager

Number

TransferObject

Camera

EndPoint

NumericStepper

Tree

CellRenderer

Error

Object

TreeDataProvider

CheckBox

FocusManager

PendingCall

TypedValue

Collection

Form

PopUpManager

UIComponent

Color

Function

PrintJob

UIEventDispatcher

ComboBox

Iterator

ProgressBar

UIObject

ComponentMixins

Key

RadioButton

Video

ContextMenu

Label

RDBMSResolver

WebService

ContextMenuItem

List

Screen

WebServiceConnector

CustomActions

Loader

ScrollPane

Window

CustomFormatter

LoadVars

Selection

XML

CustomValidator

LocalConnection

SharedObject

XMLConnector

DataGrid

Log

Slide

XUpdateResolver

DataHolder

Math

SOAPCall

 

DataProvider

Media

Sound

 

DataSet

Menu

Stage

 

DataType

MenuBar

String

 

Distinguishing Variable Names from Class Names

Variable and function names should always start with a lowercase letter. Names that start with an uppercase letter are used only for classes and data types.

Variable Typing

As you learned in Chapter 2, variable typing allows explicit declaration of what kind of data each variable should hold. Here are a number of reasons why this is a good practice:

110

Getting Started with Coding

It catches numerous errors at compile time, errors which would otherwise require significant time to track down at run time.

It allows the development environment to provide code hinting for variables.

It helps you write better code by ensuring all functions and methods properly declare their input and output types.

It causes no performance slow-downs whatsoever; it is used only at compile time.

ActionScript 1.0 provided code hinting but required that variables be named in a specific manner to take advantage of the hinting. Each variable needed to end with _code where code was a specific set of letters that needed to be remembered. Here are some examples:

var submit_btn; var username_array;

var base_mc;

var currentScore_txt;

This is still a good practice to follow, although with strong typing, you are no longer tied to specific character codes. The following versions of these variables are equally if not more understandable, even though they result in longer variable names:

var submitButton:Button; var usernameArray:Array;

var baseMovieClip:MovieClip;

var currentScoreTextField:TextField;

Whatever naming convention you decide to use, it should be apparent from the variable name what kind of data the variable contains, and the naming convention should be used consistently through your projects.

Following are suggested variable name suffixes you might consider:

111

Chapter 5

Data Type

Version 1

Version 2

 

 

 

Array

*_array

*Array

Button

*_btn

*Button

Camera

*_camera

*Camera

Color

*_color

*Color

ContextMenu

*_cm

*ContextMenu

ContextMenuItem

*_cmi

*ContextMenuItem

Date

*_date

*Date

Error

*_err

*Error

LoadVars

*_lv

*LoadVars

LocalConnection

*_lc

*LocalConnection

Microphone

*_mic

*Microphone

MovieClip

*_mc

*MovieClip

MovieClipLoader

*_mcl

*MovieClipLoader

NetConnection

*_nc

*NetConnection

NetStream

*_ns

*NetStream

PrintJob

*_pj

*PrintJob

SharedObject

*_so

*SharedObject

Sound

*_sound

*Sound

String

*_str

*String

TextField

*_txt

*TextField

TextFormat

*_fmt

*TextFormat

Video

*_video

*Video

XML

*_xml

*XML

XMLNode

*_xmlnode

*XMLNode

XMLSocket

*_xmlsocket

*XMLSocket

Type Casting

Whenever you assign one variable to another, and the variables are of different types, Macromedia Flash attempts to convert the type of the source variable to the type of the destination variable. This is a process called type casting. It generally works only when the target variable is a primitive data type (String, Number, or Boolean).

112

Getting Started with Coding

The difficulty with automatic type casting is that you do not know about it when it happens, so you might get behavior that is inconsistent with your expectations. The solution is to manually cast your variables whenever there is a discrepancy in type between two variables. The following code shows examples of casting.

//Cast a number to a string var currentDay:Number = 23;

currentDayTextField.text = String(currentDay);

//Cast a string to a number

var currentDay:Number = Number(currentDayTextField.text);

// Cast a string to a Boolean

var isBackgroundShown:Boolean = Boolean(“true”);

// Cast a number to a Boolean

var isBackgroundShown:Boolean = Boolean(1);

Try It Out

Creating Understandable Code

This example presents before and after looks at how using strong typing and good variable naming conventions helps make code easier to work with. In addition, the first code listing includes a bug that strong typing will quickly find.

1.Create a new Macromedia Flash document by selecting File New and choosing Flash Document from the New Document panel.

2.Click the first frame in the timeline, open the Actions panel (Window Development Panels Actions), and type in the following ActionScript code:

#include “tryItOut_understandableCode.as”

3.Select File Save As, name the file tryItOut_understandableCode.fla, choose an appropriate directory, and save it.

4.Create a new Macromedia Flash document and save it as tryItOut_understandableCode.as in the same directory as your .fla file.

5.Enter the following code into the new ActionScript file:

var hasBackground; var date = new Date();

var month = date.getMonth(); var startingDay;

var x; var y; var base;

date.setDate(1); startingDay = date.getDay(); hasBackground = “true”; base = _level0;

while (date.getMonth() == month)

{

113

Chapter 5

x = date.getDay() * 20 + 2;

y = Math.floor( ( startingDay + date.getDate() - 1) / 7 ) * 20 + 2;

base.createTextField(“dateField”+date.getDate(), ; this.getNextHighestDepth(), x, y, 17, 17);

base[“dateField” + date.getDate()].text = date.getDate();

if (hasBackground == true)

{

base.moveTo(x-3, y-3); base.beginFill(0xAAAAAA); base.lineStyle(1, 0x333333); base.lineTo(x-3, y+17); base.lineTo(x+17, y+17); base.lineTo(x+17, y-3); base.lineTo(x-3, y-3);

}

date.setDate(date.getDate() + 1);

}

6.Save the file, return to the Macromedia Flash project file, and select Control Test Movie.

7.Create a new Macromedia Flash document, name it tryItOut_understandableCode2.as, and save it in the same directory as the .fla file.

8.Enter the following code into the new ActionScript file:

var hasBackground:Boolean; var currentDate:Date;

var currentMonthNumber:Number; var startingDayNumber:Number; var textFieldX:Number;

var textFieldY:Number;

var baseMovieClip:MovieClip;

currentDate = new Date(); currentDate.setDate(1); startingDayNumber = currentDate.getDay(); hasBackground = true;

currentMonthNumber = currentDate.getMonth(); baseMovieClip = _level0;

while (currentDate.getMonth() == currentMonthNumber)

{

textFieldX = currentDate.getDay() * 20 + 2;

textFieldY = Math.floor((startingDayNumber + currentDate.getDate() - 1) ; / 7) * 20 + 2;

baseMovieClip.createTextField(“dateField”+currentDate.getDate(),; this.getNextHighestDepth(), textFieldX, textFieldY, 17, 17);

baseMovieClip[“dateField” + currentDate.getDate()].text = ; String(currentDate.getDate());

if (hasBackground == true)

{

114

Getting Started with Coding

baseMovieClip.moveTo(textFieldX-3, textFieldY-3); baseMovieClip.beginFill(0xAAAAAA); baseMovieClip.lineStyle(1, 0x333333); baseMovieClip.lineTo(textFieldX-3, textFieldY+17); baseMovieClip.lineTo(textFieldX+17, textFieldY+17);

baseMovieClip.lineTo(textFieldX+17, textFieldY-3); baseMovieClip.lineTo(textFieldX-3, textFieldY-3);

}

currentDate.setDate(currentDate.getDate() + 1);

}

9.Click the first frame in the timeline, open the Actions panel (Window Development Panels Actions), and modify the following ActionScript code to point to the new ActionScript file:

#include “tryItOut_understandableCode2.as”

10.Save the file, return to the Flash project file, and select Control Test Movie.

How It Works

The difference between the first and second code listings is that variable names are changed and strong typing is added. Numerous issues exist with the variable declarations and variable assignments in the first listing:

var hasBackground; var date = new Date();

var month = date.getMonth(); var startingDay;

var x; var y; var base;

startingDay = date.getDay() + 2; hasBackground = “true”;

base = _level0;

First of all, it is a bit neater to have variable assignments all happening together. Line 2 shows the variable date that differs from the data type Date by only its case, which is not a good practice.

The variable month gives no indication on its own whether it contains a numeric or string value. The x and y variables do not indicate what coordinates they hold. The variable base gives no indication of the kind of data it should hold. Finally, the variable assignment for hasBackground assigns a string to a variable of type Boolean, which causes the if statement a bit later on to always evaluate to false. With strong typing, this error is caught by the compiler.

The equivalent code from the second code listing resolves all of those issues:

var hasBackground:Boolean; var currentDate:Date;

var currentMonthNumber:Number; var startingDayNumber:Number; var textFieldX:Number;

var textFieldY:Number;

var baseMovieClip:MovieClip;

115

Chapter 5

currentDate = new Date();

startingDayNumber = currentDate.getDay() + 2; hasBackground = true;

currentMonthNumber = currentDate.getMonth(); baseMovieClip = _level0;

Also of note is the following line from the first listing:

base[“dateField” + date.getDate()].text = date.getDate();

This line assigns the date as a label to a text field. Two different data types are actually being used here. The text field expects a string label, but date.getDate() returns a number. Macromedia Flash automatically converts the data types, but it is more explicit to do it through a type casting:

baseMovieClip[“dateField” + currentDate.getDate()].text = ; String(currentDate.getDate());

The String() typecast makes it clear that the data type to be passed to the .text property is a string.

Sometimes it’s fine to let Flash automatically cast one data type to another. For instance, the preceding example shows “dateField” + currentDate.getDate(), where the number returned by currentDate.getDate() is automatically cast to a string and appended to “dateField”. In such cases, you could manually cast it using “dateField” + String(currentDate.getDate()), but when appending a string and another data type together, manual casting is not strictly needed because it’s fairly clear that the result will be a string.

Commenting

Annotating (commenting) code to make it understandable is an important part of coding. Chapter 2 introduced you to comments. Now you’ll explore how to make the best use them.

Comments in code take three forms:

Self-documenting code

Comments to explain particular issues with the code

Commented-out code

The best type of commenting to do is to make the code easily readable in the first place. That’s what’s called writing self-documenting code. It involves using variable and function names that are clear and English-like, and that readily indicate what their purpose is. If you write code that is self-documenting, you lessen the need for added comments.

Comments are not a replacement for writing clear, well-structured, easy-to-understand code. Think of comments as additional guidance to help with maintenance.

116

Getting Started with Coding

Relatively few people really know how to comment properly. Comments are not needed for every line or couple of lines, nor are they needed to explain obvious chunks of code. Instead, comments should be used to help someone through the hard parts of your code, and to document the purpose and usage for each function. Single-line comments in code always begin with two slashes: //. A few places where comments come in handy include the following, with examples:

Within complex if statements to give an English-like description of the statement:

if ((currentDay == 0 || currentDay == 6) && ; (currentMonth == 1 || currentYear == 2006)) {

//Look for weekends in February for any year and look for any weekend in 2006

Next to tricky chunks of code that someone may not want to touch unless he really knows the code:

//*****************

//*** TRICKY: Impacts client stability

//*****************

Next to a spot where a particularly hackish technique has been used:

//*****************

//*** HACK: Does not work without following line of code. I don’t know why.

//*****************

At the start of a function:

//*****************

//Name: createCalendar

//Purpose: Creates a visual calendar for the given month. Clicking on any of

//the days will call a function and pass the date to that function.

//Inputs: yearNum (Number): The year to show.

//monthNum (Number): The month to show. Starts at 0 for January.

//callbackFunction (Function): A function to call when a date button has

//been clicked on. A date object containing the selected date will

//be passed to the callback function.

//Example: function calendarCallback(selectedDate:Date):Void

//{

//trace(selectedDate);

//}

//

//createCalendar(2005, 11, calendarCallback);

//*****************

Comments are also invaluable as a debugging tool. The single-line comment can be used to remove small numbers of lines of code to test how the application behaves without them. The /* */ syntax can be used to block out larger chunks of code, including entire functions or groups of functions. (Remember to use // for comments inside a code block that you’re commenting out.)

The previous examples all used the single-line comment syntax (//). Here’s an example of how you’d comment out a block of code:

117