About using functions

Reuse blocks of code whenever possible. One way you can reuse code is by calling a function multiple times, instead of creating different code each time. Functions can be generic pieces of code; therefore, you can use the same blocks of code for slightly different purposes in a SWF file. Reusing code lets you create efficient applications and minimize the ActionScript 2.0 code that you must write, which reduces development time. You can create functions on a timeline, in a class file, or write ActionScript that resides in a code-based component, and reuse them in a variety of ways.

If you are using ActionScript 2.0, avoid writing functions on a timeline. When you use ActionScript 2.0, place functions into class files whenever possible, as the following example shows:

class Circle {
public function area(radius:Number):Number {
    return (Math.PI*Math.pow(radius, 2));
}
public function perimeter(radius:Number):Number {
    return (2 * Math.PI * radius);
}
public function diameter(radius:Number):Number {
    return (radius * 2);
}
}

Use the following syntax when you create functions:

function myCircle(radius:Number):Number { 
    //... 
} 

Avoid using the following syntax, which is difficult to read:

myCircle = function(radius:Number):Number { 
    //...
}

The following example puts functions into a class file. This is a best practice when you choose to use ActionScript 2.0, because it maximizes code reusability. To reuse the functions in other applications, import the existing class rather than rewrite the code from scratch, or duplicate the functions in the new application.

class mx.site.Utils {
    static function randomRange(min:Number, max:Number):Number {
        if (min>max) {
            var temp:Number = min;
            min = max;
            max = temp;
        }
        return (Math.floor(Math.random()*(max-min+1))+min);
    }
    static function arrayMin(numArr:Array):Number {
        if (numArr.length == 0) {
            return Number.NaN;
        }
        numArr.sort(Array.NUMERIC | Array.DESCENDING);
        var min:Number = Number(numArr.pop());
        return min;
    }
    static function arrayMax(numArr:Array):Number {
        if (numArr.length == 0) {
            return undefined;
        }
        numArr.sort(Array.NUMERIC);
        var max:Number = Number(numArr.pop());
        return max;
    }
}

You might use these functions by adding the following ActionScript to your FLA file:

import mx.site.Utils;
var randomMonth:Number = Utils.randomRange(0, 11);
var min:Number = Utils.arrayMin([3, 3, 5, 34, 2, 1, 1, -3]);
var max:Number = Utils.arrayMax([3, 3, 5, 34, 2, 1, 1, -3]);
trace("month: "+randomMonth);
trace("min: "+min);
trace("max: "+max);