Here’s a little trick I learned today regarding name spaces.

I was writing a little custom debug class and decided to grace it with its own static trace() method that would ultimately make a call to ActionScript’s global trace() function.

Basically I wanted all my tracing to go through this class but still maintain the familiar trace name. So my tracing calls would now look like this:

Debug.trace( "Oops! Something bad has happened" );

The code for my debug class went something like this:

package
{
    public class Debug
    {
        static public function trace( message :String ) :void
        {
            // Call the global trace function.
            trace( message );
        }
    }
}

Did you spot the obvious problem?

Yeah that’s right. It won’t in fact call the global version of trace() but instead recursively call the class’ static implementation until the stack explodes.

So how exactly do we get round this problem? Well you could simply change the name of the static method to something like output() or traceMsg() but I really wanted to mask the global trace() function by using its name.

We’ll here’s what to do.

Create a variable of type Function that points to the global trace() function’s definition. When you need to call the global version, make calls through the variable.

My corrected class looks something like this:

package
{
    import flash.system.ApplicationDomain;

    public class Debug
    {
        static private var globalTrace :Function;

        // Static initialiser block.
        {
            globalTrace =
                ApplicationDomain.currentDomain.getDefinition( "trace" )
                as Function;
        }

        static public function trace( message :String ) :void
        {
            // Call the global trace function for real this time.
            globalTrace( message );
        }
    }
}

A big thanks to @kaeladan for the solution. If he had a dollar for every time he’s helped me out over the years he’d be a very rich man. Unfortunately for him, he doesn’t. Follow him on Twitter – you can learn a lot from this dude.

  1. This is why flash makes me cry.

    izb
  2. ‘course I had to retweet this ‘cos I was in it 😉