3

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);  
}
Bartek
  • 2,109
  • 6
  • 29
  • 40
  • 1
    If 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). – Thomas Sep 04 '17 at 12:43
  • Yeah I've never seen this and I don't understand it. – christopher Sep 04 '17 at 12:45
  • Readability 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). – Adriaan Koster Oct 11 '21 at 11:54

2 Answers2

5

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

Marco Kunis
  • 112
  • 5
  • I got it, but I was interested whether it has deeper meaning. I mean coding conventions, readability ect. – Bartek Sep 04 '17 at 12:53
  • Ah 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. – Marco Kunis Sep 04 '17 at 12:58
1

You may have an invalid String value:

public static FooEnum fromValue(String v) {
    try {
        return valueOf(v);
    } catch (InvalidArgumentException e) {
        return FooEnum.UNKNOWN;
    }
}
daniu
  • 14,137
  • 4
  • 32
  • 53
  • Thanks, now it is clear. It means that method 'fromValue' as presented in question is pointless or added for readability purpose. – Bartek Sep 04 '17 at 12:57