使用枚举局部优化代码

开发中写出这样一段代码,如下图

                    if (entity.getTestResult()) {
                        deviceDetectDto.setTestResult("是");
                    } else {
                        deviceDetectDto.setTestResult("否");
                    }
                    if (entity.getTestType() == 0){
                        deviceDetectDto.setDetectionItem("外观和结构检查");
                    }
                    if (entity.getTestType() == 1){
                        deviceDetectDto.setDetectionItem("功能检验");
                    }
                    if (entity.getTestType() == 2){
                        deviceDetectDto.setDetectionItem("性能");
                    }

逻辑很简单,就是根据前端传过来的值判断,从而重新定义赋值。但这样有点不美观,如果有新的类型,又得再加上一个
if 判断,拓展性也不好。所以采用枚举进行优化。
首先定义两个枚举类。
分别是testResult 和DetectionItemEnum

package com.southsmart.southgnss.common.enums;

/**
 * @Enum TestResultEnum
 * @Desc 自制设备检测结果枚举类
 * @Author CJQ
 * @Class 2021/5/8 10:35
 **/
public enum TestResultEnum {

    SUCCESS(true, "是"),

    FAILURE(false, "否");

    private boolean result;

    private String description;

    TestResultEnum(boolean result, String description) {
        this.result = result;
        this.description = description;
    }

    public boolean getResult() {
        return result;
    }

    public String getDescription() {
        return description;
    }


    public static String getDescriptionByResult(boolean result) {
        if (result) {
            return SUCCESS.description;
        } else {
            return FAILURE.description;
        }
    }

}

public enum  DetectionItemEnum {

    APPEARANCEANDSTRUCTUREINSPECTION(0,"外观和结构检查"),


    FUNCTIONTEST(1,"功能检验"),


    PEIRFORMANCE(2,"性能");


    private String type;

    private Integer number;

    DetectionItemEnum(Integer number ,String type){
        this.number = number;
        this.type = type;
    }


    public int getNumber(){
        return number;
    }

    public String getType(){
        return type;
    }

   public static String getTypeByNum(Integer number){
        for(DetectionItemEnum detectionItemEnum : values()){
            if (detectionItemEnum.getNumber() == number) {
                return detectionItemEnum.getType();
            }
        }
        throw new RuntimeException("不存在该类型");
    }
}

使用枚举类简化代码

                    deviceDetectDto.setTestResult(TestResultEnum.getDescriptionByResult(entity.getTestResult()));
                    deviceDetectDto.setDetectionItem(DetectionItemEnum.getTypeByNum(entity.getTestType()));                   

这样就能去掉繁多的if else了。
在次记录一下枚举的应用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值