减少if else
1. 三目运算符
可以理解为条件 ?结果1 : 结果2 里面的?号是格式要求。也可以理解为条件是否成立,条件成立为结果1,否则为结果2。
实例:
public String handle(int code) {if (code == 1) {return "success";} else {return "error";}
}
对于条件只有两个的情况下,可以使用三目运算符来解决。
优化:
public String handle(int code) {return code == 1 ? "success" : "error";
}
当条件较少时,可以增强代码阅读性,减少代码臃肿。
当条件过多时,就不能用三目运算符了,我们可以使用枚举类。
实例:
/*** 根据code获取支付方式* @param code* @return*/
public String handle(int code) {if (code == 1) {return "支付宝";} else if (code == 2) {return "微信";} else if (code == 3) {return "qq";} else if (code == 4) {return "银行卡";} else {return "现金";}
}
如果后面又增加code,就需要再写if-else,会越来越长并不好维护。
我们可以采用枚举类来优化。
优化:
public enum PayTypeEnum {ALIPAY(1, "支付宝"),WECHAT(2, "微信"),QQ(3, "QQ"),BANK_CARD(4, "银行卡"),CASH(5, "现金");private static Map<Integer, String> payTypeMap = new HashMap();static {for (PayTypeEnum payTypeEnum : PayTypeEnum.values()) {payTypeMap.put(payTypeEnum.getCode(), payTypeEnum.getType());}}public static String get(int code) {if (payTypeMap.containsKey(code)) {return payTypeMap.get(code);}return payTypeMap.get(5);}private int code;private String type;public String getType() {return type;}public void setType(String type) {this.type = type;}public int getCode() {return code;}public void setCode(int code) {this.code = code;}PayTypeEnum(int code, String type) {this.code = code;this.type = type;}
}
public static void main(String[] args) {String res = PayTypeEnum.get(5);System.out.println(res);
}
只需要传入相应的code即可获取数据,不需要再写过长的if-else了。如果需要新增,在枚举类里拓展就好了。
对Object进行判空,是这样的。
实例:
public void handle() {StudentDo studentDo = null;if (studentDo == null) {System.out.println("对象为空");} else {if (studentDo.getName() == null) {System.out.println("学生姓名不能为空");} else if (studentDo.getScore() == null) {System.out.println("学生成绩不能为空");}}
}
我们可以使用断言类
优化:
public void handle1() {StudentDo studentDo = null;Assert.notNull(studentDo, "对象为空");Assert.notNull(studentDo.getName(), "学生姓名不能为空");Assert.notNull(studentDo.getScore(), "学生成绩不能为空");
}
后面再进行业务操作即可。
实例:
public void handle() {StudentDo studentDo = null;if (studentDo != null) {//业务操作} else {return;}
}
优化:
public void handle1() {StudentDo studentDo = null;if (studentDo == null) {return;}//业务操作
}
实例:
String sta="hello";
if(sta==null){System.out.println("");
}else{System.out.println(sta);
}
优化:
String sta="hello";
String a=Optional.ofNullable(sta).orElse("");
System.out.println(a);