Java – Whether to use enum vs map vs config file

configurationenumjava

I have ~30 resources each having ~10 attributes. I want to store some information about each attribute. Ex: its multiplicity, it RW (Read/Write), RO (Read only), longName, shortname.

So I was thinking of storing it in a Enum like:

public enum Attributes {

    U_RESOURCETYPE(true, "RW", "resourceType", "rt"),
    U_RESOURCEID(false, "RO", "resourceID","ri"),
    //...
}

But this lead to 300 constants (30 resources * 10 attributes).

I could also use a config file or a Singleton Enum with a Map as member.

What is the best possible way to achieve this ??

Best Answer

I assume these are really constants, not configuration values - i.e. they don't change between invocations or deployments.

In that case I'd store it in Java files - no complicated parsing from the config file, you can leverage type safety etc.

Your approach with enums is fine for a lot of cases, but the problem here is the number of attributes - enum constructor contains too many arguments so it's easy to get lost in them, switch order of arguments etc.

In your case I'd probably create something like this:

class Attributes {
    public static Attributes U_RESOURCETYPE = new Attributes()
            .setMultiplicity(true)
            .setRw("RW")
            .setLongName("resourceType")
            .setShortName("rt");

    public static Attributes U_RESOURCEID = new Attributes()
            .setMultiplicity(true)
            .setRw("RO")
            .setLongName("resourceID")
            .setShortName("ri");

    private boolean multiplicity;
    private String rw;
    private String longName;
    private String shortName;

    private Attributes() {}

    private Attributes setMultiplicity(boolean multiplicity) {
        this.multiplicity = multiplicity;
        return this;
    }

    private Attributes setRw(String rw) {
        this.rw = rw;
        return this;
    }

    private Attributes setLongName(String longName) {
        this.longName = longName;
        return this;
    }

    private Attributes setShortName(String shortName) {
        this.shortName = shortName;
        return this;
    }
}

It gives you typesafety and clarity, but it's a bit more laborious ...

Related Topic