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

Viewed 1621

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").

3 Answers
  • 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.

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.

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

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