Using namespaces for access control.

Using your own namespaces can be a good way to add another level of access control to class libraries that sits somewhere between public and internal.

If you want to expose methods to classes in different packages, but not make them readily available to the whole of the outside world then this is a good way to do it. The Flex framework itself makes quite heavy use of the mx_internal namespace for inter-package communication and undocumented APIs

First is to make the namespace. This can be done in an actionscript file that contains the following:

 
package com.as3offcuts.namespaces 
{ 
     public namespace offcuts_internal; 
} 

That's it. Now you can import this namespace in your classes and either declare methods using it instead of public/internal etc. or call methods from other classes using it. The following demonstrates using the new namespace on an instance method:

 
package com.as3offcuts.somepackage 
{ 
import com.as3offcuts.namespaces.offcuts_internal; 

use namespace offcuts_internal; 
 
public class SomeClass 
 { 
    offcuts_internal function doSomething():void 
    { 
        trace("something"); 
    } 
 } 
}

There are three elements in the above example. The first is to import the namespace, much as you would import a class. The second is the use namespace declaration, and the third is use it in place of public or internal or whatever.

To then access this method from another class simply repeat the first two steps (import the namespace and the 'use namespace ... ' line.) and then call the method as you would call a public or internal one.

 
package com.as3offcuts.otherpackage 
{ 
 import com.as3offcuts.namespaces.offcuts_internal; 
 
use namespace offcuts_internal; 
 
public class SomeOtherClass 
 { 
    public function SomeOtherClass() 
    { 
        var someClass:SomeClass = new SomeClass(); 
        someClass.doSomething(); 
     }
 }
}

In terms of access control, as mentioned above, this sits somewhere between public and internal. It would be nice if it was just library level, but in reality anyone can import your namespace and use all the methods. They would however need to know about the namespace in first place. On the flip side though, another use for this is undocumented APIs, in which case you may actually want other people to use it.

As a foot note, importing and using the mx_internal namespace opens up undocumented functionality in the Flex framework. As the mx_internal.as file warns though, these methods are liable to change in future releases.