Java 枚举属性最佳实践

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5983776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:50:38  来源:igfitidea点击:

Java Enum property best practice

javaenumsenumeration

提问by JustinKSU

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();
}

回答by Jon Skeet

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.

第一个显然对我来说看起来更清晰 - 它利用了枚举的每个元素都有一个固定的字符串 URL 的共性,该 URL 在初始化时是已知的。您在第二个版本的每个实现中有效地重复了该“逻辑”。在每种情况下,您都覆盖了一个方法以提供相同的逻辑(“只返回一个在编译时已知的字符串”)。我更喜欢保留覆盖行为的变化。

I suggest making the urlfield private though, in the first.

url不过,我建议首先将该领域设为私有。

回答by John Kane

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

查看Josh Bloch 的 Effective Java本章中的第21 项。它讨论了类型安全的枚举模式。

回答by DerMike

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.

如果您以某种方式忘记添加 url,我会选择第一个,因为编译器会抱怨。第二个会让你在这里犯错误。