How Java enumeration classes are used in the production environment


preface

   Java enumeration is widely used in projects. When working on projects, many people will encounter the need to maintain the state of some business scenarios. They often define a constant class and add the state constants related to business scenarios. But in fact, the definition of business status in production environment projects is mostly completed by enumeration classes, because it is clearer and clearer. It is very convenient to customize different methods to obtain the corresponding business status value.


   the following codes are code snippets of projects that have been launched in the production environment for reference only.



use

   it is generally divided into several parts: determining the business scenario status, defining enumeration classes, customizing query methods, testing results, etc.

1. Determine business scenario status

Take the actual project in my work as an example, the smart hospital needs to use the payment function when registered and outpatient payment. We have implemented the following payment forms: WeChat small program payment, WeChat H5 payment, Alipay small program payment, Alipay life code payment, and WeChat medical insurance payment.
   then, we can define an enumeration class for these payment forms for special maintenance. In the future, when we need to add, modify and delete, we only need to modify this enumeration class.


2. Define enumeration class
public enum PayTypeEnum {

    WEI_XIN_MINI_APP("1", "wxma", "Wechat applet payment"),

    WEI_XIN_H5("2", "wxh5", "WeChat H5 payment"),

    ZFB_MINI_APP("3", "zfbma", "Alipay applet payment"),

    ZFB_H5("4", "zfbh5", "Alipay life code payment"),

    WEI_XIN_MEDICAL("5", "wxmedical", "Wechat medical insurance payment");

    private final String id;
    private final String code;
    private final String label;

    PayTypeEnum(final String id, final String code, final String label) {
        this.id = id;
        this.code = code;
        this.label = label;
    }

    public String getId() {
        return id;
    }

    public String getCode() {
        return code;
    }

    public String getLabel() {
        return label;
    }

}

3. Custom query method

   enumeration class we have defined id, code and label. In the process of using, we may need to obtain enumeration values according to id, code (the two I define most of the time), or even label. Therefore, we can define our own query methods as needed.

/**
 * Get enumeration object based on id
 * @param id 
 */
public static PayTypeEnum findById(String id) {
    for (PayTypeEnum type : PayTypeEnum.values()) {
        if (type.getId().equals(id))
            return type;
    }
    return null;
}

/**
 * Get enumerated objects according to code
 * @param code 
 */
public static PayTypeEnum findByCode(String code) {
    for (PayTypeEnum type : PayTypeEnum.values()) {
        if (type.getCode().equals(code))
            return type;
    }
    return null;
}

  for perfection, we can also define another method to check the enumeration type.

/**
 * Check whether the payment type is valid
 * @param id 
 */
public static void check(String id) {
    if (StringUtils.isEmpty(id)) {
        throw new BadRequestAlertException("Invalid payment type", "PayTypeEnum", "Invalid payment type");
    }
    for (PayTypeEnum type : PayTypeEnum.values()) {
        if (type.getId().equals(id)) {
            return;
        }
    }
    throw new BadRequestAlertException("Invalid payment type", "PayTypeEnum", "Invalid payment type");
}

  the final code is as follows:

import com.web.rest.errors.BadRequestAlertException;
import org.springframework.util.StringUtils;

public enum PayTypeEnum {

    WEI_XIN_MINI_APP("1", "wxma", "Wechat applet payment"),

    WEI_XIN_H5("2", "wxh5", "WeChat H5 payment"),

    ZFB_MINI_APP("3", "zfbma", "Alipay applet payment"),

    ZFB_H5("4", "zfbh5", "Alipay life code payment"),

    WEI_XIN_MEDICAL("5", "wxmedical", "Wechat medical insurance payment");

    private final String id;
    private final String code;
    private final String label;

    PayTypeEnum(final String id, final String code, final String label) {
        this.id = id;
        this.code = code;
        this.label = label;
    }

    public String getId() {
        return id;
    }

    public String getCode() {
        return code;
    }

    public String getLabel() {
        return label;
    }

    /**
     * Get enumeration object based on id
     * @param id 
     */
    public static PayTypeEnum findById(String id) {
        for (PayTypeEnum type : PayTypeEnum.values()) {
            if (type.getId().equals(id))
                return type;
        }
        return null;
    }

    /**
     * Get enumerated objects according to code
     * @param code
     */
    public static PayTypeEnum findByCode(String code) {
        for (PayTypeEnum type : PayTypeEnum.values()) {
            if (type.getCode().equals(code))
                return type;
        }
        return null;
    }

    /**
     * Check whether the payment type is valid
     * @param id 
     */
    public static void check(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new BadRequestAlertException("Invalid payment type", "PayTypeEnum", "Invalid payment type");
        }
        for (PayTypeEnum type : PayTypeEnum.values()) {
            if (type.getId().equals(id)) {
                return;
            }
        }
        throw new BadRequestAlertException("Invalid payment type", "PayTypeEnum", "Invalid payment type");
    }

}

4. Test effect
public static void main(String[] args) {

   System.out.println("============= Gets the value of the enumeration class =============");
   System.out.println("obtain id: " + PayTypeEnum.WEI_XIN_MINI_APP.getId());
   System.out.println("obtain code: " + PayTypeEnum.WEI_XIN_MINI_APP.getCode());
   System.out.println("obtain label: " + PayTypeEnum.WEI_XIN_MINI_APP.getLabel());


   System.out.println("============= Get the value according to the custom query method =============");
   System.out.println("according to id Get enumeration object:" + PayTypeEnum.findById("3"));
   System.out.println("according to code Get enumeration object:" + PayTypeEnum.findByCode("zfbma"));


   System.out.println("============= Type validity check =============");
   System.out.print("Check 1:");
   PayTypeEnum.check("1");
   System.out.println();
   System.out.print("Check 2:");
   PayTypeEnum.check("999");
}

   print as follows:

============= Gets the value of the enumeration class =============
obtain id: 1
 obtain code: wxma
 obtain label: Wechat applet payment
============= Get the value according to the custom query method =============
according to id Get enumeration object: ZFB_MINI_APP
 according to code Get enumeration object: ZFB_MINI_APP
============= Type validity check =============
Check 1:
Check 2: invalid payment type

Process finished with exit code 0



summary

   most of the definitions of Java enumeration classes are related to business scenarios, but for definitions similar to business status values, it is best to use enumeration classes, which is convenient for maintenance and reading. However, the styles of each engineer and R & D team are different. Only in terms of personal work experience over the years, they often participate in a project and form a large number of enumeration classes in the later stage, Instead of a large number of constant classes, there is only one constant class at most, and too many words cannot be maintained at all. Especially after personnel changes, new colleagues feel headache about a large number of constant classes, but enumeration classes can clearly express the business scenario and usage.



   if you like, please click... Ah, no, click like. If you think it's useful, you can also click collection and pay attention to it ~ (o... o)


Keywords: Java

Added by zechdc on Thu, 03 Feb 2022 10:41:08 +0200