javaenumsenumeration

Java Enum property best practice


I've seen two approaches to handling enums with properties. Is one better than the other?

As a property:

public enum SEARCH_ENGINE {
    GOOGLE("http://www.google.com"),
    BING("http://www.bing.com");

    private final String url;

    private SEARCH_ENGINE(String url) {
        this.url = url;
    }

    public String getURL() {
        return url;
    }
}

As a method:

public enum SEARCH_ENGINE {
    GOOGLE {
        public String getURL() {return "http://www.google.com";}
    },
    BING {
        public String getURL() {return "http://www.bing.com";}
    };

    public abstract String getURL();
}

Solution

  • The first clearly looks cleaner to me - it makes use of the commonality that each element of the enum will have a fixed String URL which is known at initialization. You're effectively repeating that "logic" in each implementation in the second version. You're overriding a method to provide the same logic ("just return a string which is known at compile-time") in each case. I prefer to reserve overriding for changes in behaviour.

    I suggest making the url field private though, in the first.