My Android project duplicated declarations between Enum and string.xml

I have String arrays to use for Spinner or such.

 <string-array name="Animal"> <item >Cat</item> <item >Dog</item> <item >Rabbit</item> <item >Bird</item> </string-array> 

I have a container class that contains values ​​entered by the user or selected from Spinner . Member variables are mostly primitives or Enum .

 public class Container { protected int index; protected int age; protected String name; protected Animal pet; } 

Here's how one of the Enum classes is defined (note that this is a simpler version, and in my actual code there are a few more methods or variables, and each Enum instance is uppercase, like CAT).

 public enum Animal { Cat, Dog, Rabbit, Bird, } 

As you can see, I am practically repeating the same thing in Enum and XML. This is not very good by DRY. Who should I remove, and how to do it?

At this point, I tend to preserve Enum , as it is functionally more universal than XML, and no less maintained. The only possible problem I can worry about is its performance. They may require more memory, as well as some additional encoding features.

+4
source share
1 answer

If you want to avoid duplication, you must save Enum, and then you fill in the program key using for(Animal animal:Animal.values()) {...} .

You can use the name Enum as a key to get a localized label or similar things.

+1
source

All Articles