Search code examples
javaenumscorrectness

is my Enumeration correct?


All over our project, we have this kind of enums. They works just fine, but we are not sure about them.

Specially with the getDocumentType(String) method.

Is there a way to avoid the iteration over all the Enums field ?

public enum DocumentType {

    UNKNOWN("Unknown"),
    ANY("Any"),
    ASSET(Asset.class.getSimpleName()),
    MEDIA(Media.class.getSimpleName()),
    MEDIA35MM(Media.class.getSimpleName() + " 35mm");


    private String label;

    private DocumentType(String label) {
        this.label = label;
    }

    public String getLabel() {
        return label;
    }

    public static DocumentType getDocumentType(String label){
        for(DocumentType documentType : DocumentType.values()){
            if(documentType.getLabel().equals(label)){
                return documentType;
            }
        }
        return UNKNOWN;
    }
}

Edit : Check the newacct response. She's fine too.


Solution

  • You're going to have to do that iteration somewhere, due to the restrictions in writing enums. In an ideal world, you would populate a static Map from within DocumentType's constructor, but that's not allowed.

    The best I can suggest is performing the iteration once in a static initializer, and storing the enums in a lookup table:

    public enum DocumentType {
    
        .... existing enum stuff here
    
        private static final Map<String, DocumentType> typesByLabel = new HashMap<String, DocumentType>();
        static {
            for(DocumentType documentType : DocumentType.values()){
                typesByLabel.put(documentType.label, documentType);
            }
        }
    
        public static DocumentType getDocumentType(String label){
            if (typesByLabel.containsKey(label)) {
                return typesByLabel.get(label);
            } else {
                return UNKNOWN;
            }
        }
    }
    

    At least you won't be doing the iteration every time, although I doubt you'll see any meaningful performance improvement.