枚举类替代switch和ifelse
问题:
下游传入参数,需要对参数判断然后重新赋值对外提供,之前的做法是switch,转成枚举类判断
模拟对象
/**
* @Author: liuxuewei
* @Date: 2022/6/28 14:04
* @Description:
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CarInfo {
Integer id;
Integer value;//车型value
String desc;//车型汉字
}
模拟问题
//下游只传了value值,需要对value判断从而取值
//模拟下游数据
List<CarInfo> list = new ArrayList<>();
list.add(new CarInfo(1,1,""));
list.add(new CarInfo(2,2,""));
list.add(new CarInfo(3,3,""));
list.add(new CarInfo(4,4,""));
//之前的做法,或者直接4个ifelse摆起来
String carDesc = "";
for (CarInfo carInfo : list) {
switch (carInfo.getValue()) {
case 1:
carDesc = "低端车";
break;
case 2:
carDesc = "中端车";
break;
case 3:
carDesc = "高端车";
break;
default:
carDesc = "无推荐";
break;
}
carInfo.setDesc(carDesc);
}
System.out.println(list);
定义枚举类
/**
* @Author: liuxuewei
* @Date: 2022/6/28 14:02
* @Description:
*/
@Getter
@AllArgsConstructor
public enum CarNameEnum {
LowEndCar(1,"低端车"),
MiddleEndCar(2,"中端车"),
HighEndCar(3,"高端车");
private Integer value;
private String desc;
//新增方法通过遍历value获取desc
public static String getDescByValue(int value){
String result = "无推荐";//匹配不到就无推荐
for (CarNameEnum e: CarNameEnum.values()){
if(e.getValue() == value){
result = e.getDesc();
break;
}
}
return result;
}
}
枚举类解决
//枚举类做法
for (CarInfo carInfo : list) {
carInfo.setDesc(CarNameEnum.getDescByValue(carInfo.getValue()));
}
System.out.println(list);
优点:
避免在业务代码中直接使用“魔法值”
用枚举类替代原有业务逻辑,使得主业务代码和逻辑更为清晰,业务分工更为明确。
之后新增其他类型的话,只需在枚举类中新增枚举类型就可以了,不用改动原有业务代码
评论区