Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 430
user2652379 Avatar asked Sep 15 '25 19:09

user2652379


1 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.
like image 137
Peter Walser Avatar answered Sep 18 '25 09:09

Peter Walser