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

Share:
10,002
Bartek
Author by

Bartek

Updated on June 14, 2022

Comments

  • Bartek
    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
      Thomas over 6 years
      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).
    • christopher
      christopher over 6 years
      Yeah I've never seen this and I don't understand it.
    • Bartek
      Bartek over 6 years
      Thanks, I am new to programming, so I was puzzled by that.
    • Adriaan Koster
      Adriaan Koster over 2 years
      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).
  • Bartek
    Bartek over 6 years
    I got it, but I was interested whether it has deeper meaning. I mean coding conventions, readability ect.
  • Bartek
    Bartek over 6 years
    Thanks, now it is clear. It means that method 'fromValue' as presented in question is pointless or added for readability purpose.
  • Marco Kunis
    Marco Kunis over 6 years
    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.