| < Day Day Up > |
2.4 On with the Show!
In this chapter, we summarized the
Let's get started! |
| < Day Day Up > |
| < Day Day Up > |
Chapter 3. Datatypes and Type Checking
ActionScript 2.0 defines a wide variety of datatypes. Some datatypes are native to the language itself (e.g.,
String
,
Number
, and
Boolean
). Others are included in the Flash Player and are available throughout all Flash movies (e.g.,
For a primer on ActionScript's datatypes, see Chapter 3 of
ActionScript for Flash MX: The Definitive Guide
(O'Reilly), available online at
http://
In addition to using ActionScript 2.0's datatypes, developers can add new datatypes to a program by creating classes (covered in Chapter 4) and interfaces (covered in Chapter 8). Every value in ActionScript 2.0 belongs to a datatype, whether built-in or programmer-defined. When we work with a value, we must use it only in ways supported by its datatype. For example, we can call getTime( ) on a Date object, but we must not call gotoAndPlay( ) on a Date object, because the Date class does not support the gotoAndPlay( ) method. On the other hand, we can call gotoAndPlay( ) on a movie clip because that method is defined by the MovieClip class. In order for an object-oriented program to work properly, every operation performed on every object should succeed. That is, if a method is invoked on an object, the object's class must actually define that method. And if a property is accessed on an object, the object's class must define that property. If the object's class does not support the method or property, that aspect of the program will fail. Depending on how we write our code, either the failure will be silent (i.e., cause no error message), or it will cause an error message that appears in the Output panel. The error message helps us diagnose the problem.
We
someDate.geTime( ) // WRONG! No such method! Our call to geTime( ) will fail because the Date class defines no such method.
And what happens if we invoke
indexOf( )
on a value we think is a
String
, but the value turns out to be a
Number
? The call to
indexOf( )
will fail, because the
Number
class doesn't support the
indexOf( )
method. Example 3-1
Example 3-1. A mistaken datatype assumption
// WRONG! This code mistakenly assumes that
getDay( )
returns
// a string indicating the day (e.g., "Monday", "Tuesday"),
// but
getDay( )
actually returns a number from 0 to 6.
var today;
today = new Date( ).getDay( );
if (today.indexOf("Friday") == 1) {
trace("Looking forward to the weekend!");
}
// The correct code should be:
var today;
today = new Date( ).getDay( );
// Sunday is 0, Monday is 1, ... Friday is 5.
if (today == 5) {
trace("Looking forward to the weekend!");
}
In a large program, these kinds of problems can be exceedingly difficult and
To help us recognize and isolate datatype-
var variableOrPropertyName : datatype Specifying an item's datatype is often called datatype declaration . For example, this line of code declares that the datatype of the variable count is Number : var count:Number; We'll learn more about datatype syntax later in this chapter.
ActionScript 2.0
{% if main.adsdop %}{% include 'adsenceinline.tpl' %}{% endif %} Type checking helps us guarantee that a program will run the way we intend it to. To see how, let's return to Example 3-1 in which a programmer mistakenly attempted to invoke indexOf( ) on a numeric value. The source of the programmer's problem was the incorrect assumption that Date.getDay( ) returns a string, when in fact, it returns a number. The programmer originally assigned the return value of getDay( ) to the variable today without specifying today 's datatype: var today; today = new Date( ).getDay( );
Because the code doesn't specify the datatype of the variable
today
, the ActionScript 2.0 compiler has no way of knowing that the programmer expects
today
to contain a string. The compiler, hence, allows any type of data to be stored in
today
. The
In ActionScript 2.0, the programmer can prevent the problem from going unnoticed by declaring the intended datatype of the variable
today
, as
// ":String" is the datatype declaration
var today
:String
;
today = new Date( ).getDay( );
In this case, the programmer is still "wrong." His assumption that getDay( ) returns a string is still a problem, but it is no longer a hidden problem. Because the programmer has stated his assumption and intent, the ActionScript 2.0 compiler dutifully generates this error: Type mismatch in assignment statement: found Number where String is required.
This error message should elicit great joy. Why? Because
known
errors are usually trivial to fix once you understand the error message. The error message states that the code requires a string but
An inexperienced developer might immediately say, "Aha! The problem is that
The programmer originally assumed that Date.getDay( ) returns a String when it in fact returns a Number . But the programmer has no control over the value returned by getDay( ) , which is defined by the Date class and not the programmer. So the solution is to accommodate the return value's correct datatype by storing it in a variable of type Number instead of type String . Example 3-2 demonstrates. Example 3-2. Fixing a datatype mismatch error
// This line declares
today
's type as a
Number.
var today:Number
// Assign the return value of
getDay( )
to
today
. In this version,
// the variable's datatype matches the datatype of the value returned
// by
getDay( )
, so no type mismatch error occurs.
today = new Date( ).getDay( );
// Sunday is 0, Monday is 1, ... Friday is 5.
if (today == 5) {
trace("Looking forward to the weekend!");
}
Example 3-3 demonstrates an alternative case in which the programmer really does need a string for display purposes. As usual,
getDay( )
returns a number, so in this case, the programmer must manually convert the number to a
Example 3-3. One way to derive a string from a number
// This line declares
today
's type as a
Number
// and assigns the return value of
getDay( )
to
today
.
var today:Number = new Date( ).getDay( );
// Populate an array with the names of the days.
var dayNames:Array = ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"];
// Make a new variable that stores the human-readable day.
var todayName:String = dayNames[today];
// Display the human-readable day in a text field.
currentDay_txt.text = todayName;
// Display the human-readable day in the Output panel.
trace(todayName);
So there are two ways to solve a type mismatch error. One way is to declare your variable to be of the correct type and write (or rewrite if necessary) your code to deal with the datatype
Regardless, without ActionScript 2.0's type checking, the original datatype mismatch might have gone unnoticed.
ActionScript 2.0's approach to datatyping is called
static typing
. In static typing, the datatype of variables and other data containers is fixed at compile time so that the compiler can guarantee the validity of every method called and property accessed in the program. Because datatypes are fixed in a statically typed language, the compiler can say, "I know this variable contains a
Date
object, and I know that the
Date
class doesn't define a method by the
The
// ActionScript 1.0 code... var x = 10; // Look ma, I'm a number! x = "hello world"; // Now I'm a string! And you could access a nonexistent method or property without errors: // ActionScript 1.0 code... var s = new Sound( ); s.thisMethodDoesntExist( ); // No error in ActionScript 1.0! As we learned earlier, the preceding code ”without any modifications ”would not cause errors even in ActionScript 2.0! That's because ActionScript 2.0's type checking is an opt-in system. In order to activate type checking, you must specify the datatype of the variable, property, parameter, or return value being used. Hence, to cause the preceding ActionScript 1.0 code to generate helpful errors in ActionScript 2.0, we declare the variables' datatypes, as follows: // ActionScript 2.0 code... var x:Number = 10; // Here, x 's datatype starts as Number . x = "hello world"; // This attempt to store a string in x causes an error! var s:Sound = new Sound( ); s.thisMethodDoesntExist( ); // ERROR! No such method... // Here's the output: **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 3: Type mismatch in assignment statement: found String where Number is required. x = "hello world"; // This attempt to store a string in x causes an error! **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 6: There is no method with the name 'thisMethodDoesntExist'. s.thisMethodDoesntExist( ); // ERROR! No such method... Because ActionScript 2.0 lets you circumvent type checking by omitting type declarations, its specific variety of static typing is called weak static typing , where "weak" means that the language will check for type errors at compile time if told to do so but also offers programmers ways to disable the type checking system. Languages such as Java that do not let the programmer circumvent type checking are called strongly typed . Generally speaking, it pays to develop all ActionScript 2.0 projects with datatyping enabled for all variables, properties, parameters, and return values (i.e., by declaring their types using post-colon syntax). Even when upgrading ActionScript 1.0 code, try to add as much type information as you can; the more information you provide, the more feedback you'll get from the compiler when you do something wrong.
|
| < Day Day Up > |