views:

490

answers:

1

I've just got back to MIDP development after some 4 years of .NET 2 and Java 5 and 6. During that time I got to like using enums quite a lot.

Enum is a language feature that allows a developer to have more confidence in some parts of his code, specially for being able to avoid or detect errors earlier (during compilation). Some other advantages can be found here: http:// java.sun.com/j2se/1.5.0/docs/guide/language/enums.html

I found it strange that I couldn't find them in MIDP 2.0. I've got this error message:

"Type 'enum' should not be used as an identifier, since it is a reserved keyword from source level 1.5"

I had some experience in Java 1.4 a while back, but I didn't remember this. There sure are some features of newer versions of your high-level languages that you get to take for granted...

Anyway, here is a good recommendation for what to do without them (if you're developing MIDP or dealing with code prior to Java 5): http:// www.javacamp.org/designPattern/enum.html

Summing it up (for more details and a good explanation, follow the previous link. Many thanks to the original author):

//The typesafe enum pattern
public class Suit {
    private final String name;

    public static final Suit CLUBS =new Suit("clubs");
    public static final Suit DIAMONDS =new Suit("diamonds");
    public static final Suit HEARTS =new Suit("hearts");
    public static final Suit SPADES =new Suit("spades");    

    private Suit(String name){
        this.name =name;
    }
    public String toString(){
        return name;
    }

}

Do you have any other different approaches to this issue?

+1  A: 

The problem with MIDP is that it is stuck at Java language level 1.2 (some say 1.3 or 1.4 but thats not the point) and Enums were introduced in 1.5. Your pattern is a step into the right direction, but lacks some features of "real" enums, like assigning an ordinal number to each constant.

You might run into similar issues with generics, annotations, etc. which were also introduced in 1.5. There are tools to convert Java 1.5 back to 1.2, some are listed here. Like that, you should be able to code in 1.5 and run on MIDP. Note, however, that using those tools will complicate your build process considerably, while the solution you mentioned does not.

Brian Schimmel