Abstract Classes in AS3
As we started building a new library at work, we were pondering what was the best strategy for abstract classes. Despite arguments to the contrary, we respectfully believe that abstract classes are useful! A quick Google search produces a lot of alternatives. Here are some of them.
All of these examples assume that the class is called AbstractExample and that any necessary imports have been made. I will concentrate just on the constructor method.
getQualifiedClassName Approach @ PixelBreaker
public function AbstractExample()
{
if(Class(getDefinitionByName(getQualifiedClassName(this))) == AbstractExample)
throw new Error("AbstractExample must not be directly instantiated");
}
toString Approach @ Tink
public function AbstractExample()
{
if(toString() == "[object AbstractExmample]")
throw new Error("AbstractExample must not be directly instantiated");
}
Object Constructor Approach @ various
public function AbstractExample()
{
if(Object(this).constructor === AbstractExample)
throw new Error("AbstractExample must not be directly instantiated");
}
Self Reference Approach @ JoshTalksFlash
Note that with this approach (unlike the others) you have work to in the instantiating class, calling super(this); at the top of your constructor.
public function AbstractExample(self:AbstractExample)
{
if(self != this)
throw new Error("AbstractExample must not be directly instantiated");
}
A review
The lack of a genuine abstract class is a little annoying. It is interesting to see the different mechanisms by which various coders have worked around the problem. For me though, what I have coined the Object Constructor Approach is the compelling choice. It is quick to write (or template in Eclipse), doesn’t need any imports, and generally looks the most clean. For our new code library, the choice seems straightforward.
-
Alan
-
alecmce
-
alecmce
-
Keith Peters
