Sunday, 25 October 2009

Generalize Methods

This one I saw in the "Actionscript 3 Cookbook" by Joey Lott, Darron Schall, Keith Peters and published by O'Reilly. Although it's on the first chapter of the book, it may come handy most of the times.

This recipe applies when you have a method and you want to use it several times, but with slightly different numbers of arguments, like calculating the average number. You can calculate the average between 2 numbers, or maybe, 7.

Lets  make a example:

public function average (num1:Number, num2:Number):void{
   trace("The average number is: "+(num1+num2)/2;

You call this method like this:


The answer will be:

The average number is: 4.5

So how can I call the average method with a different number of arguments?

In the first place, you don't specify the number of arguments you put in the method, when you define it.
 Then, you must have a cycle inside the method, that will read all the arguments when you call it. 
Do it like this:

public function average():Number{
  var sum:Number=0;

  for(var i:Number=0; i
  return sum/arguments.length;

The keyword arguments will retrieve the number and the value of the arguments that you place when you call a method.

then call the function like this:

var value:Number=average(2,3,4);


var value:Number=average(5,6,7,8,9,10);

This is a nice feature