简体   繁体   中英

Public final in enum's instance variables

i would like to know if it's a common accepted practice to give public visibility to final data fields in 'enum' instances, and name them using the CONSTANT_CASE. I know that it's not strictly correct, but often I use enum instead of final Classes to simplify the code.
An example, I use:

public enum PropertyType {

   STRING("string", String.class, "generico"),
   BOOLEAN("boolean", Boolean.class, "vero/falso"),
   NUMBER("number", Double.class, "numerico"),
   INTEGER("integer", Long.class, "intero");

   public final String JSON_TYPE;
   public final Class JAVA_TYPE;
   public final String DESCRIPTION;

   private PropertyType(String jsonType, Class javaType, String description) 
   {
       if (jsonType == null)
           throw new IllegalArgumentException("json type can't be null");

       if (javaType == null)
           throw new IllegalArgumentException("java type can't be null");

       this.JSON_TYPE = jsonType;
       this.JAVA_TYPE = javaType;
       this.DESCRIPTION = description;
   }
}

instead of

public class PropertyType {
    public static final class STRING {
        public static final String JSON_TYPE="string";
        public static final Class JAVA_TYPE=String.class;
        public static final String DESCRIPTION="generico";
    }

    ...
    ...

    private PropertyType() {}
}

Both the options let you use syntax like 'PropertyType.STRING.DESCRIPTION', but the first is easier to code and less redundant, plus it's faster to expand while the latter it's long to code with a lot of copy and paste... Since the purpose of the two it's the same, why require a different naming convention?

While this question is primarily opinion-based, I would say the following:

  1. upper case field names are adopted to be used only for static constants
  2. for this particular case more logical make these object variables private and add conventional getters for them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM