'Java enum - best practice to access enum ? direct access or using valueOf()?
Let's say I have a simple enum:
public enum Status {
ACTIVE("A", "Active Account"),
INACTIVE("I", "Inactive Account");
private String code;
private String description;
Status(String code, String description) {
this.code = code;
this.description = description;
}
public String getDescription() {
return description;
}
}
and that's 2 options to get the description, both returning the same result
1. Status.ACTIVE.getDescription()
2. Status.valueOf("ACTIVE").getDescription()
I used to do it with option 1 because I personally think that
1. More straight forward
2. Reduce typo compares to option 2
3. Any changes to enum will immediately get error in IDE or compile error instead of runtime error
but I wish to know is there any benefits using option 2? And what is the best practice to access the enum ?
Solution 1:[1]
Depends on a case by case basis. If you need to query that using some input string you need valueOf.
ValueOf is technically slower since it runs string matching subroutines, so unless you need that part, the first one is a direct reference call which the compiler interprets as direct memory slot value retrieval rather than a function which must be ran at runtime.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | EverNight |
