
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
42
|
Chapter 3: Datatypes and Type Checking
}
// Pass values with different datatypes to x and y.
// No errors occur because the parameters x and y are not typed.
trace(combine(4,5)); // Displays: 9
trace(combine("hello ", "world")); // Displays: hello world
trace(combine(_root, "hello world")); // Displays: _level0hello world
While the preceding code may seem more convenient because of its flexibility, it
actually causes more work and problems than a typed version would. When the
method is not typed, the program code—not the compiler—must decide whether
the method’s return value is useful or nonsensical. The program becomes responsi-
ble for guarding against basic data errors rather than relying on the compiler to do so
automatically. For example, if we wanted to be sure that the result of combine(4, 5)
were a number, we’d have to use:
if (typeof combine(4, 5) == "number") {
// Okay to proceed...
} else {
trace("Unusable value returned by combine( ).");
}
The preceding code successfully safeguards against nonnumeric uses of combine( ),
but it takes five lines to do so! What’s more, it is required every time the program
uses the combine( ) method, and similar code would be needed for any other calls to
methods without return types. That is, absent compile-time datatype checking, the
programmer ...