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

April 04, 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

Trackback Pings

TrackBack URL for this entry:
http://weblogs.macromedia.com/mtadmin/mt-tb.cgi/7274

Comments

This technique is particularly nice in AS3, compared to Java, because AS3 lets you switch on any type. But I'd still consider adding a string property to the class, for use in debugging.

Posted by: Peter at April 4, 2006 01:07 PM

Yeah cool,
I have been doing similar, thought id try it after using the internal struc & enum class types in c#.

Cam

Posted by: Campbell at April 4, 2006 02:23 PM

I blogged something like that for AS 2 way back...
http://blog.jasonnussbaum.com/?p=48

With some added toString methods and all that jazz...

Posted by: Jason Nussbaum at April 4, 2006 02:39 PM

Peter: Great comments. I hadn't thought about the AS3 "switch on any type" aspect.

Jason: Glad to see we're on the same page. Thanks for the link.

Posted by: Sho at April 4, 2006 02:59 PM

But in Java 5 you can at least switch on "real" enums.

Btw: If only Adobe would not prevent private and protected constructors, it would make life so much easier for creating singletons and faking enums and abstract classes. Still don't know why they are not allowed any more...

Posted by: Jens Halm at April 5, 2006 08:08 AM

I'm glad that Java 5 has enums and generics. Maybe we can get them into AS4? :-)

I started writing a reply here, but it ended up getting quite long so I'm moving it to a new entry. Let me know what you think.

Posted by: Sho at April 5, 2006 09:03 AM