What is benefit from using fromValue function instead of valueOf, java enums?
10,002
Solution 1
You may have an invalid String value:
public static FooEnum fromValue(String v) {
try {
return valueOf(v);
} catch (InvalidArgumentException e) {
return FooEnum.UNKNOWN;
}
}
Solution 2
Think about an enum that has a string property with a different value then the name of the enum.
public enum FooEnum {
A("foo"),
B("bar"),
;
...
}
Then you need such an method for a lookup of the property values. See also this answer
Author by
Bartek
Updated on June 14, 2022Comments
-
Bartek almost 2 years
I see some programmers use in enums structure function called fromValue. What is it purpose, if we can use valueOf? For example, I found something like this:
public static FooEnum fromValue(String v) { return valueOf(v); }
-
Thomas over 6 yearsIf the implementation is like this then we can only guess - and my guess would be it's meant to be more readable (I'm not saying it is though).
-
christopher over 6 yearsYeah I've never seen this and I don't understand it.
-
Bartek over 6 yearsThanks, I am new to programming, so I was puzzled by that.
-
Adriaan Koster over 2 yearsReadability can also be improved by standardization. Maybe this team agreed to always use the above signature for getting an enum from a String, to make it uniform for both complex cases where there is error handling or value mapping, and simple cases (like above).
-
-
Bartek over 6 yearsI got it, but I was interested whether it has deeper meaning. I mean coding conventions, readability ect.
-
Bartek over 6 yearsThanks, now it is clear. It means that method 'fromValue' as presented in question is pointless or added for readability purpose.
-
Marco Kunis over 6 yearsAh okay. We use it like @daniu mentioned, to handle invalid values and throwing an exception that indicates a developer failure. So it is more an internal conding convention.