3

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. Should I avoid using name()?

For example,

public enum Example1 {FOO, BAR}

Refactoring FOO name to FOO2 will brake 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").

user2652379
  • 782
  • 3
  • 9
  • 27

3 Answers3

5
  • Business logic should use the enum value, never the name() directly. Reason: even if the name changes, the semantic (same enum value as before) remains the same.
  • The name() is used when serializing/deserializing values. 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.
    Changing the name might require data migration or adaptions in 3rd party code.
Peter Walser
  • 15,208
  • 4
  • 51
  • 78
  • 1
    Is the same applied to `valueOf` and `toString` method? – user2652379 Sep 14 '18 at 08:47
  • 2
    valueOf is directly coupled to the name, and neither name() nor valueOf() can be overridden, so: yes. toString, on the other hand, can be overridden and be used to display additional information / fields of the enum. – Peter Walser Sep 14 '18 at 09:01
2

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.

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.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
-2

When using enum type, I always compares enum itself but not enum's name(string).

Example2.FOO.equals(Example2.getEnumByName("FOO"));
Jerry Zhou
  • 189
  • 1
  • 2
  • 13
  • I got string values from URL parameters. It can be converted to an enum value, but parameters are so easy to be tempered by clients. So I choose to compare strings in this case. – user2652379 Sep 14 '18 at 07:35
  • 1
    The question is about renaming an enum constant in the source code (AKA refactoring it) without breaking any code that relied on that name. Here, the code would be broken in the same way as when using `Example1.FOO.name().equals("FOO")`. – Tomasz Linkowski Sep 14 '18 at 08:05