Hi all,

I'm not sure if this issue has been discussed before (couldn't find anything on the mail list thou...), but what do you guys think of using type-safe enum constants as keys instead of plain String values?

I assume there is a general understanding here that using enum constants instead of strings is the "right thing" to do, but obviously there are also important reasons not do so (legacy code, interface changes, pre-Java1.5 stuff etc...). But I guess the most important one is that Java enums never have been designed to work in a generic form (namely: no abstract enums and/or enum inheritance). So there is no way to put an enum placeholder in a library, and provide the concrete enum values in the implementing application. An issue which I and other people already have bemoaned (see http://java.dzone.com/articles/java-should-have-extended for example), but it is nevertheless a given fact we have to live with in the foreseeable future... :(

Having said that, I just see two ways of using enum constants for fetching config values. For one just using a lame config.getWhatever(MyEnum.key.name()) everywhere. It would be a start, but well.. not really what I was searching for...

The other solution I see would be to mark the enums with a marker interface, and take that as the key placeholder, such as:

public interface Configurable {
    public String name();
}

public interface Configuration {
boolean getBoolean(Configurable key);
    (other methods follow here...)
}

In the application you would define the keys in an enum such as that:

public enum MyKeys implements Configurable {
    FOO,
    BAR,
    ...;
}

Then you could access the config values in real type-safe way:

boolean myValue = config.getBoolean(MyKeys.BAR);

Another advantage would be that enum constants can be easily enriched with meta-data (via a custom annotation), for example:

public enum MyKeys implements Configurable {
    @ConfigData(
        defaultValue="foo",
        type=String.class,
        mandatory=true,
        pattern="[a-z]{1,4}",
        reload=false)
    FOO,
    ...;
}

The possibilities here are endless (see also my pet project at www.soplets.org exploring more in-depth the meta-data aspects of annotations), but for a beginning having just enum constants alone would be a good start in my view...

What do you think about that proposal, does that make any sense? Any other options I have overlooked so far? Looking forward hearing your opinions...

regards,

Chris May















Reply via email to