INCLUDE_DATA

Typesafe Enum Pattern in Flex

The standard way to represent an enumerated type in Action Sctipt 3.0 is the int Enum pattern:

public static const FILE: int = 0;
public static const EDIT: int = 1;
public static const FORMAT: int = 2;
public static const VIEW: int = 3;

This pattern has many problems, such as:

* Not typesafe – Since a FILE, EDIT etc are just an int you can pass in any other int value where a enum value is required
* No namespace – You must carefuly use names to avoid collisions with other int enum types.
* Brittleness – Because int enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined.
* Printed values are uninformative – Because they are just ints, if you print one out all you get is a number, which tells you nothing about what it represents, or even what type it is.

Here I use typesafe enum pattern, use a class to represent constants:

public class TypesafeEnum
{

private var name : String;

public static const FILE :TypesafeEnum = new TypesafeEnum("file");
public static const EDIT :TypesafeEnum = new TypesafeEnum("edit");
public static const FORMAT :TypesafeEnum = new TypesafeEnum("format");
public static const VIEW :TypesafeEnum = new TypesafeEnum("view");		

public function TypesafeEnum(name : String)
{
	this.name = name;

}

public function toString(): String {
	return name;
}

}
[/code]

test case may look like below

[code lang="actionscript"]
private function testCase(): void {

	testEnum(TypesafeEnum.FILE);

}

private function testEnum(thisValue: TypesafeEnum): void {

	switch (thisValue) {
		case TypesafeEnum.EDIT:
			trace(TypesafeEnum.EDIT.toString());
			break;
		case TypesafeEnum.FILE:
			trace(TypesafeEnum.FILE.toString());
			break;
		case TypesafeEnum.FORMAT:
			trace(TypesafeEnum.FORMAT.toString());
			break;
		case TypesafeEnum.VIEW:
			trace(TypesafeEnum.VIEW.toString());
			break;				

	}

}