« Flex auto complete text input control v0.6 | Main | AS3 -- on the lack of private and protected constructors »

April 4, 2006

AS3 technique -- using object instances as "enums"

Just after posting the updated version of the CompletionInput control, it occured to me that I should read through the source code to make sure there's nothing too strange lurking in there.

One thing that might warrant some explanation is why I used object instances to represent "enums". This is a technique that should be familiar to Java developers but may not be familiar to all AS developers.

In LoopResult.as, I define constants like this:

public class LoopResult {
    public static const KEEP_GOING : LoopResult = new LoopResult();
    public static const STOP : LoopResult = new LoopResult(); 
}

Whereas in CompletionInput.as, I define them like this:

public class CompletionInput extends mx.controls.TextInput 
{
    public static const COMPLETION_FAILED    : int = 1;
    public static const COMPLETION_SUCCEEDED : int = 2;
    public static const COMPLETION_ASYNC     : int = 3;
    ...
}

In both cases, I use these static members as if they were "enums".

	...
	return LoopResult.KEEP_GOING;
or
	return CompletionInput.COMPLETION_SUCCEEDED;

The main difference between the two is that the first version is typesafe -- I can declare my function as returning a LoopResult, not an int or a String.

PRO:
CON:

Posted by sho at April 4, 2006 10:16 AM