简体   繁体   English

什么时候可以使用Enum的名字()

[英]When is it OK to use an Enum's name()

Variables' name can be changed and shouldn't affect logic. 变量的名称可以更改,不应影响逻辑。 But name() method in Enum returns a constant name as a value so it can break existing code. 但是Enum中的name()方法返回一个常量名称作为值,因此它可以破坏现有代码。 Should I avoid using name() ? 我应该避免使用name()吗?

For example, 例如,

public enum Example1 {FOO, BAR}

Refactoring FOO name to FOO2 will brake Example1.FOO.name().equals("FOO") . FOO名称重构为FOO2将生成Example1.FOO.name().equals("FOO")

public enum Example2 {
    FOO("FOO"),
    BAR("BAR");

    String code;

    private Example2(final String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}

In this case, changing FOO name to FOO2 will not brake Example2.FOO.getCode().equals("FOO") . 在这种情况下,将FOO名称更改为FOO2将不会制动Example2.FOO.getCode().equals("FOO")

  • Business logic should use the enum value , never the name() directly. 业务逻辑应该使用枚举值 ,而不是直接使用name() Reason: even if the name changes, the semantic (same enum value as before) remains the same. 原因:即使名称发生变化,语义(与之前相同的枚举值)也保持不变。
  • The name() is used when serializing/deserializing values. 序列化/反序列化值时使用name() This affects the database (when using the names for O/R mapping), serialized data stored in files or transmitted over the wire (JSON/XML/YAML/... serialization), log entries and more. 这会影响数据库(使用O / R映射的名称时),存储在文件中或通过线路传输的序列化数据(JSON / XML / YAML / ...序列化),日志条目等。
    Changing the name might require data migration or adaptions in 3rd party code. 更改名称可能需要在第三方代码中进行数据迁移或调整。

Your suspicion that it is unwise to use it generally because it leaks an implementation detail is correct. 您怀疑使用它通常是不明智的,因为它泄漏了实现细节是正确的。 If you had a colour enum with a RED value, it would be wrong to report to a program user the colour of something using colour.name() , because the user might need a message in a language other than English, and ALL CAPS text would usually be inappropriate. 如果您有一个带有RED值的颜色enum ,那么使用colour.name()向程序用户报告某些颜色是错误的,因为用户可能需要使用非英语语言的消息和所有CAPS文本通常是不合适的。

Using it in code used by programmers to help debug problems is OK. 在程序员用来帮助调试问题的代码中使用它是可以的。 Such as exception messages, because they should not be presented to normal program users . 例如异常消息,因为它们不应该呈现给普通程序用户

使用枚举类型时,我总是比较枚举本身而不是枚举的名称(字符串)。

Example2.FOO.equals(Example2.getEnumByName("FOO"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM