一、提前返回(Guard Clauses)
适用场景:当 else
块仅用于处理异常或边界条件时。
- 优化前:
if (isValid) { doSomething(); } else { return; }
- 优化后:
if (!isValid) return; // 提前处理异常,主流程保持简洁 doSomething();
- 优势:减少嵌套层级,逻辑更线性化。
二、使用枚举(Enum)
适用场景:多分支状态映射(如状态码、配置值)。
- 示例:
// 优化前 if ("1".equals(status)) { ... } else if ("2".equals(status)) { ... } // 优化后 public enum StatusEnum { UN PAID("1", "未支付"), PAID("2", "已支付"); // 通过枚举直接获取值 } String desc = StatusEnum.of(status).getDesc();
- 优势:集中管理状态,避免冗余判断。
三、Map/字典驱动
适用场景:根据键值对执行不同操作。
- 示例:
// 优化前 if (type == 1) { action1(); } else if (type == 2) { action2(); } // 优化后 Map actions = new HashMap<>(); actions.put(1, () -> action1()); actions.getOrDefault(type, () -> defaultAction()).run();
- 优势:动态扩展分支,无需修改原有逻辑。
四、三元运算符(Ternary Operator)
适用场景:简单的二元条件赋值。
- 示例:
// 优化前 int score = 85; if (score > 60) { result = "Pass"; } else { result = "Fail"; } // 优化后 String result = score > 60 ? "Pass" : "Fail";
- 注意:避免嵌套使用,保持可读性。
五、Optional 处理空值
适用场景:非空判断与默认值处理。
- 示例:
// 优化前 if (order != null) { return order.getId(); } else { return -1; } // 优化后 return Optional.ofNullable(order) .map(Order::getId) .orElse(-1);
- 优势:链式调用,避免空指针异常。
六、策略模式(Strategy Pattern)
适用场景:多分支逻辑需独立扩展。
- 示例:
interface PaymentStrategy { void pay(); } class AlipayStrategy implements PaymentStrategy { ... } class WechatPayStrategy implements PaymentStrategy { ... } // 使用策略工厂动态选择 PaymentStrategy strategy = StrategyFactory.create(type); strategy.pay();
- 优势:符合开闭原则,新增逻辑无需修改原有代码。
七、表驱动法(Table-Driven Methods)
适用场景:基于配置表的条件映射。
- 示例:
// 将条件与操作存入 Map 或数据库 Map discounts = new HashMap<>(); discounts.put("SUMMER2023", 0.8); discounts.put("BLACKFRIDAY", 0.5); double rate = discounts.getOrDefault(code, 1.0);
- 优势:动态配置,降低代码耦合度。
八、正则表达式替代多重判断
适用场景:字符串匹配规则复杂。
- 示例:
# 优化前 if len(password) < 8: return False if not any(char.isdigit() for char in password): return False # 优化后 import re pattern = r'^.*[0-9].*[A-Za-z].*$' return bool(re.match(pattern, password))
- 优势:集中管理匹配规则,减少冗余代码。
九、责任链模式(Chain of Responsibility)
适用场景:多层级处理请求。
- 示例:
abstract class Handler { private Handler next; public void setNext(Handler next) { ... } public abstract void handleRequest(); } // 各处理器依次处理请求 Handler h1 = new Handler1(); Handler h2 = new Handler2(); h1.setNext(h2); h1.handleRequest();
- 优势:解耦处理逻辑,支持动态添加步骤。
十、合并条件表达式
适用场景:多个条件返回相同结果。
- 示例:
// 优化前 if (city.equals("北京")) return "首都"; if (city.equals("上海")) return "经济中心"; // 优化后 if ("北京".equals(city) || "上海".equals(city)) { return "一线城市"; }
- 优势:减少重复判断,提升可读性。
注意事项
- 避免过度优化:若逻辑简单,保留
if-else
可能更清晰。 - 结合设计模式:策略模式、状态模式等适用于复杂业务场景。
- 文档与注释:优化后需补充注释,确保团队协作。
通过上述方法,可显著降低代码复杂度,提升可维护性。具体选择需根据场景权衡,核心原则是 “让代码更易读,而非追求形式上的简洁”。