Chapter 3. Datatypes and Type Checking

 <  Day Day Up  >  

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., Color , Date , and TextField ). Still other datatypes are defined by components that can be added individually to Flash movies (e.g., List , RadioButton , and ScrollPane ).

For a primer on ActionScript's datatypes, see Chapter 3 of ActionScript for Flash MX: The Definitive Guide (O'Reilly), available online at http:// moock .org/asdg/samples .

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 certainly strive to use objects appropriately. We don't intentionally call gotoAndPlay( ) on a Date object, because we know that the gotoAndPlay( ) method isn't supported by the Date class. But what happens if we make a typographical error? What if we accidentally invoke geTime( ) (missing a "t") instead of getTime( ) on a Date object?

 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 demonstrates this situation.

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 time-consuming to track down. In both the geTime( ) example and the indexOf( ) example, unless ActionScript reports an error in the Output panel, we'll have a hard time identifying the issue and locating its cause in our program.

To help us recognize and isolate datatype- related problems in our code, we use ActionScript 2.0's type checking capabilities. That is, we can ask ActionScript to check the values in our program and warn us with an error message if it detects a value being used in some inappropriate way. But there's a catch: in order to provide this service, ActionScript 2.0 requires that you formally declare the datatype of every variable, property, parameter, and return value that you want checked. To declare the datatype of a variable or property, we use this general form, referred to as post- colon syntax :

 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.

As a best practice, in an ActionScript 2.0 program, you should declare the datatype of every variable, property, function parameter, method parameter, function return value, and method return value.


ActionScript 2.0 performs type checking on every variable, property, parameter, and return value that has a declared datatype. If your code attempts to store incompatible types of data in an item that has a declared datatype, a type error appears in the Output panel at compile time. Later we'll learn precisely what constitutes an "incompatible type," but for now, you can just assume intuitively that two types are incompatible when they don't match (i.e., String and Number , Array and Sound , etc.).

Variables , properties, parameters, and return values without a declared datatype are not type checked. If you omit the datatype, omit the colon used in post-colon syntax as well.


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 preceding code simply stores the return value of getDay( ) into today . Because the return value of getDay( ) is a number, today stores a number, not a string. This eventually leads to a problem with the program.

In ActionScript 2.0, the programmer can prevent the problem from going unnoticed by declaring the intended datatype of the variable today , as follows (changes shown in bold):

  // ":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 encountered a number instead. We need to work backward to understand the message's meaning. Why did the code "require" a string? It was just obeying the programmer's request! The compiler thinks the code requires a string because (and for no other reason than) the programmer declared today 's datatype as String . The error message tells the programmer that he is breaking his own constraints; the programmer declared a string-only data container (the variable today ) and tried to place a numeric value (the return value of getDay( ) ) into it.

An inexperienced developer might immediately say, "Aha! The problem is that awful number where a string belongs! I must change the number into a string!" Don't fall into that trap, and don't be misled by the error message.

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 human-readable string. The trick is to use the number returned by getDay( ) to extract a string from an array of day names .

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 accordingly . The alternative is to write extra code to convert the returned data to the datatype you desire .

Regardless, without ActionScript 2.0's type checking, the original datatype mismatch might have gone unnoticed.

figs/as1note.gif ActionScript 1.0 had no form of type checking whatsoever and generated no type-based errors. This left developers with the arduous chore of hunting down unintentional typos and misuses of objects.

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 name geTime( ) (remember our earlier typo?), so I'll warn the programmer with an error message." Handy indeed.

figs/as1note.gif In ActionScript 1.0, methods were often added to a class via the prototype object. This technique is not recognized by the ActionScript 2.0 compiler in most cases. Therefore, if you are compiling code for ActionScript 2.0, invoking a prototype -based method on a variable with a declared datatype may cause a compile-time error. In ActionScript 2.0, there is no way to add a method to most classes at runtime; the practice is considered officially illegitimate. You should define all methods in class files, prior to compiling. See Section 3.4 for exceptions to this rule. See Section 4.1.1 in Chapter 4 for related information.

The converse of static typing is dynamic typing , in which each value is associated with a datatype at runtime, not at compile time. With dynamic typing, data containers such as variables can change datatypes at runtime because type information is associated with each value, not with each data container. In a dynamically typed language, such as Python or Smalltalk, type mismatch errors can occur at runtime but they can't be detected a priori at compile type. ActionScript 2.0 does not provide any dynamic type facilities and generates no runtime type errors. ActionScript 1.0, by contrast, provided no type checking at all and therefore could not be considered statically typed nor dynamically typed ”rather, it was considered untyped . ActionScript 1.0 effectively let you do whatever you wanted with any kind of data. For example, in ActionScript 1.0, you could change the type of a variable from one type to another without errors:

 // 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.

Macromedia's documentation uses the term "strict data typing" to refer to ActionScript's type checking capabilities. Although Macromedia uses "strict" as a synonym for "static," they are not technically the same. So be aware that the terms "strict," "static," and "strong" are often interchanged recklessly in common discussion, as are "weak" and "dynamic."


 <  Day Day Up  >  


Essential ActionScript 2.0
Essential ActionScript 2.0
ISBN: 0596006527
EAN: 2147483647
Year: 2004
Pages: 177
Authors: Colin Moock

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net