开发者

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) {
        thi开发者_运维技巧s.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();
}


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.


Take a look at item 21 from this chapter of Josh Bloch's Effective Java. It talks about the type safe enum pattern.


I'd go with the first since the compiler complains if you somehow forget to add a url. The second would let you make errors here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜