开发中写出这样一段代码,如下图
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了。
在次记录一下枚举的应用