适用场景:当 else
块仅用于处理异常或边界条件时。
if (isValid) {
doSomething();
} else {
return;
}
if (!isValid) return; // 提前处理异常,主流程保持简洁
doSomething();
适用场景:多分支状态映射(如状态码、配置值)。
// 优化前
if ("1".equals(status)) { ... } else if ("2".equals(status)) { ... }
// 优化后
public enum StatusEnum {
UN PAID("1", "未支付"), PAID("2", "已支付");
// 通过枚举直接获取值
}
String desc = StatusEnum.of(status).getDesc();
适用场景:根据键值对执行不同操作。
// 优化前
if (type == 1) { action1(); } else if (type == 2) { action2(); }
// 优化后
Map actions = new HashMap<>();
actions.put(1, () -> action1());
actions.getOrDefault(type, () -> defaultAction()).run();
适用场景:简单的二元条件赋值。
// 优化前
int score = 85;
if (score > 60) {
result = "Pass";
} else {
result = "Fail";
}
// 优化后
String result = score > 60 ? "Pass" : "Fail";
适用场景:非空判断与默认值处理。
// 优化前
if (order != null) {
return order.getId();
} else {
return -1;
}
// 优化后
return Optional.ofNullable(order)
.map(Order::getId)
.orElse(-1);
适用场景:多分支逻辑需独立扩展。
interface PaymentStrategy {
void pay();
}
class AlipayStrategy implements PaymentStrategy { ... }
class WechatPayStrategy implements PaymentStrategy { ... }
// 使用策略工厂动态选择
PaymentStrategy strategy = StrategyFactory.create(type);
strategy.pay();
适用场景:基于配置表的条件映射。
// 将条件与操作存入 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))
适用场景:多层级处理请求。
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
可能更清晰。