Max Blog

My Blog

If you can’t overload them, namespace them

ActionScript3 does not support method overloading, but why do you want to overload methods?

In my opinion there are two answers:

  1. You want to pass the same method different amount of parameters
  2. You want to have methods with same name but different behavior

In first case AS3 provides you the feature of default parameter values:

?View Code ACTIONSCRIPT
function foo(var a : String, var i : int = 0): void{
  for(;i<=0 ; i++){
    trace(a);
  }
}

So you can call method foo with one parameter “foo(‘hello’)” or with two “foo(‘hello’, 2)”

Let’s talk about the second case: same name different behavior.

In this case you can use namespaces.

?View Code ACTIONSCRIPT
package my {
 
	public class NamespaceExamp {
 
		namespace NS1;
		namespace NS2;
 
		NS1 function foo() : void {
		}
		NS2 function foo() : void {
		}
	}
}

The interesting part of namespaces is also that those are not declaration but URI based (like in XML).

Have a look at this example:

?View Code ACTIONSCRIPT
package my {
 
	public class NamespaceExamp {
 
		namespace NS1 = "myNS";
		namespace NS2 = "myNS";
 
		NS1 function foo() : void {
		}
		NS2 function foo() : void {
		}
	}
}

In this case foo is a duplicate method and it doesn’t matter that we declared two namespaces, their URIs are same so both foo declarations are in the same namespace. BTW if you don’t declare URI explicitly as in the first namespace example than the runtime will generate a namespace by the location of declaration (complicated stuff).

Another interesting fact is that the keyword “public” is also a namespace, but with empty URI.

So this is also a duplicate declaration:

?View Code ACTIONSCRIPT
package my {
 
	public class NamespaceExamp {
 
		namespace NS1 = "";
 
		NS1 function foo() : void {
		}
		public function foo() : void {
		}
	}
}
posted by admin in AS3 Creative point of view and have Comments (3)

3 Responses to “If you can’t overload them, namespace them”

  1. Nico Zimmermann says:

    Hey Max :)

    This is very interessting… I created this example:

    var builder : SomeBuilder = new SomeBuilder();
    builder.buildRectangle(0, 0, 100, 100);
    builder.byPoint::buildRectangle(new Point(0, 0), new Point(100, 100));
    builder.byRectangle::buildRectangle(new Rectangle(0, 0, 100, 100));

    …it works :) Great idea!

  2. Carlo Blatz says:

    Hey Max,

    awesome! Well done. Thanks a lot for pushing FDT :) .

    cheers Carlo

  3. admin says:

    I am glad to help :)

Place your comment

Please fill your data and comment below.
Name
Email
Website
Your comment
Before you submit form:
Human test by Not Captcha