一.过多的 if else会使得代码的质量变差,主要体现在以下:
1.可读性降低:大量的 if…else 结构会使代码变得复杂,难以阅读和理解。长链的条件分支会让其他开发者(甚至是你自己在一段时间后)难以跟踪代码的流程。
2.可维护性差:当逻辑需要改变或扩展时,你可能需要修改多个地方的 if…else 语句,这增加了出错的风险。每次添加新的条件或更改现有条件时,都可能引入错误。
3.性能影响:虽然现代处理器的分支预测技术可以减轻 if…else 对性能的影响,但在高频率执行的循环或关键路径中,过多的条件分支仍然可能导致流水线停顿,从而影响性能。尤其是在嵌入式或实时系统中,这种影响可能更加显著。
4.代码冗余:相似的条件检查在多处重复出现会导致代码冗余,违反了 DRY(Don’t Repeat Yourself)原则。
5.设计问题:频繁使用 if…else 可能表明你的设计模式选择不当。例如,你可以考虑使用工厂模式、策略模式或状态模式等设计模式来替换复杂的条件判断,以达到更好的代码结构和可扩展性。
6.测试难度增加:每个 if…else 分支都可能需要单独的测试用例,这使得单元测试和集成测试变得更加困难和耗时。
二.if else不仅违背设计原则,还不利于扩展
@PostMapping("pay")
public String pay(String payType) {
switch (payType) {
case "weiXin":
return "微信支付";
case "alipay":
return "支付宝支付";
case "unionPay":
return "银联支付";
default:
return "其它支付";
}
}
如上代码,当新增或减少支付方式时,就要加一个case或删一个case,不仅违背开闭原则,还使得代码可读性降低。
三.使用策略模式优化
1.先定义一个抽象类或接口PayStrategy
public interface PayStrategy {
String pay();
}
2.具体的支付方式继承或实现PayStrategy
public class AliPay implements PayStrategy {
@Override
public String pay() {
return "支付宝支付";
}
}
3.定义一个PayContextHolder类,在此类中定义一个Map,key为支付类型,value为该支付类型对应的全限定类名,最后定义一个方法,根据支付方式支付。使用反射创建具体的支付对象,进行支付。
@Component
public class PayContextHolder {
public static final Map<String, String> payStrategy = new HashMap<>();
static {
payStrategy.put("weiXin", "com.hyper.strategy.WeiXinPay");
payStrategy.put("alipay", "com.hyper.strategy.AliPay");
}
public String doPay(String payType) {
try {
if (StringUtils.isBlank(payType)) {
return "未知的支付方式";
}
String clazz = payStrategy.get(payType);
PayStrategy pay = (PayStrategy) Class.forName(clazz).newInstance();
return pay.pay();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}