10

I have a situation that I presume is pretty common. I have a Java enum:

public enum Flavour { CHOCOLATE, STRAWBERRY }

I have a custom attribute defined in attrs.xml:

<attr name="flavour">
    <enum name="chocolate" value="0" />
    <enum name="strawberry" value="1" />
</attr>

But this feels really fragile. It relies on me manually mapping from the attribute to the enum correctly.

If someone adds "SARDINE" to the end of enum Flavour then it obviously won't be automatically added to the attribute definition. That's fair enough.

But worse, if someone adds "SARDINE" in the middle of the enum, it will break xml layouts that use "strawberry".

How do people overcome this? I've considered using string (and using Flavour.valueOf()), but I was hoping there might be a cleaner solution out there.

Martin
  • 3,703
  • 2
  • 21
  • 43

1 Answers1

-3

As long as you keep the Flavour enum up to date and in sync with the flavour attribute, it should be fine, but if you really don't want to have to worry about the order then don't use indices. Instead go with Strings as you have considered.

public enum Flavor {
  CHOCOLATE, STRAWBERRY

  public static Flavor get(String s) {
     s = s.toLowerCase();
     if(s.equals("chocolate")) {
       return CHOCOLATE;
     } else {
       return STRAWBERRY;
     }
  }
}
Alex Fu
  • 5,509
  • 3
  • 31
  • 40
  • Well yes, I mentioned that approach in my question as a possible work-around, but it gives up all the advantages of using a custom attribute in the first place. With your implementation, if someone sets the value to "choclate", then it will mysteriously get set to STRAWBERRY at runtime. Another implementation might throw an exception on an unmatched value, but that's a runtime check whereas custom attributes give you compile-time checking. – Martin Dec 14 '13 at 11:40