Java - enum valueOf "override" naming convention

Say you have the following enumeration :

public enum Color { RED("R"), GREEN("G"), BLUE("B"); private String shortName; private Color(String shortName) { this.shortName = shortName; } public static Color getColorByName(String shortName) { for (Color color : Color.values()) { if (color.shortName.equals(shortName)) { return color; } } throw new IllegalArgumentException("Illegal color name: " + shortName); } } 

Since enum is a special case where you cannot just override the valueOf function, what is a naming convention to get around this and implement valueOf (string name)?

 getColorByName(String name) getValueOf(String name) permissiveValueOf(String name) customValueOf(String name) forName(String name) getEnum(String name) getColor(String name) 

Later Edit: I see Bloch in Effective Java 2nd edition. suggests something in the getInstance () lines (chapter 1, paragraph 1). Just add another option.

+6
source share
3 answers

You are definitely right, you cannot override Enum#valueOf() , since it is a static Enum class method.

I do not think there is a naming convention. As you have already pointed out, there are several examples in Java:

I will not use getEnum , since you are not getting Enum itself, but rather a value. Using forName() is not suitable here, R not a red name.

I would prefer:

  • fromString() since this is the opposite of toString() ;
  • getColor() for compatibility with the standard Java library.
+13
source

Also consider the following:

 Color fromName(String name); Color fromShortName(String shortName); Color fromCode(String code); 
+2
source

I would use a couple:

 Color fromValue(String value) String toValue() 

This is what I found most suitable in my listings.

+1
source

Source: https://habr.com/ru/post/955167/


All Articles