本文目录导读:

- 卫语句(Guard Clause)精简多重
if-else嵌套 - 使用 switch 表达式替代 if-else 链(Java 14+)
- 三元运算符精简简单条件赋值
- 使用 Stream + Lambda 精简循环与判断
- 使用 Optional 消除 null 检查
- 枚举策略模式(Enum + Strategy)替代复杂分支
- 精简流程图
针对Java流程控制结构的精简,核心原则是:利用语言特性减少嵌套,用表达式替代语句,并为常见模式寻找更优的替代方案。
以下是具体的精简案例和技巧:
卫语句(Guard Clause)精简多重 if-else 嵌套
痛点:深层嵌套的 if-else 导致可读性极差。
-
冗余案例:
public void process(Order order) { if (order != null) { if (order.isPaid()) { if (order.getItems().size() > 0) { // ... 核心业务逻辑 System.out.println("处理订单"); } } } } -
精简方案(卫语句):
public void process(Order order) { // 提前返回,消除嵌套 if (order == null) return; if (!order.isPaid()) return; if (order.getItems().isEmpty()) return; // 核心业务逻辑直接主流程 System.out.println("处理订单"); }
使用 switch 表达式替代 if-else 链(Java 14+)
痛点:多个条件判断变量值,使用 if-else 显得冗长。
-
冗余案例:
String type = "A"; String result; if ("A".equals(type)) { result = "Alpha"; } else if ("B".equals(type)) { result = "Beta"; } else { result = "Unknown"; } -
精简方案(switch 表达式):
String type = "A"; // 直接赋值,无需break,更简洁 String result = switch (type) { case "A" -> "Alpha"; case "B" -> "Beta"; default -> "Unknown"; };
三元运算符精简简单条件赋值
痛点:简单的 if-else 赋值占用了6行代码。
-
冗余案例:
int score = 85; String grade; if (score >= 60) { grade = "Pass"; } else { grade = "Fail"; } -
精简方案(三元运算符):
int score = 85; String grade = (score >= 60) ? "Pass" : "Fail";
-
注意:三元运算符嵌套过多会降低可读性,建议同时处理不超过两个条件。
使用 Stream + Lambda 精简循环与判断
痛点:传统的 for 循环配合 if 判断进行集合过滤,代码量大。
-
冗余案例:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); List<String> longNames = new ArrayList<>(); for (String name : names) { if (name.length() > 3) { longNames.add(name); } } -
精简方案(Stream API):
List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); List<String> longNames = names.stream() .filter(name -> name.length() > 3) .collect(Collectors.toList());
使用 Optional 消除 null 检查
痛点:为了防止空指针,不断进行 if (obj != null) 和 if (obj != null && obj.getXxx() != null) 的嵌套检查。
-
冗余案例:
User user = findUser(); String city = ""; if (user != null) { Address address = user.getAddress(); if (address != null) { city = address.getCity(); } } return city; -
精简方案(Optional):
User user = findUser(); return Optional.ofNullable(user) .map(User::getAddress) .map(Address::getCity) .orElse(""); // 如果任意环节为空,返回空字符串
枚举策略模式(Enum + Strategy)替代复杂分支
痛点:根据某个值执行不同算法,使用巨型 switch 或 if-else 难以扩展。
-
冗余案例:
public int calculate(int a, int b, String operator) { switch (operator) { case "+": return a + b; case "-": return a - b; case "*": return a * b; case "/": return b != 0 ? a / b : 0; default: throw new IllegalArgumentException(); } } -
精简方案(枚举封装行为):
// 定义枚举,内部包含计算逻辑 public enum Operator { PLUS { int apply(int a, int b) { return a + b; } }, MINUS { int apply(int a, int b) { return a - b; } }, TIMES { int apply(int a, int b) { return a * b; } }, DIVIDE { int apply(int a, int b) { return b != 0 ? a / b : 0; } }; abstract int apply(int a, int b); } // 使用:一行搞定 public int calculate(int a, int b, Operator op) { return op.apply(a, b); }
精简流程图
原始代码(复杂/冗余) --> 精简后(清晰/高效) ----------------------------------------------- 多层 if 嵌套 --> 卫语句 / 提前 return if-else 判断值 --> switch 表达式 (Java 14+) 简单 if-else 赋值 --> 三元运算符 手动 for + if 过滤 --> Stream + Lambda 深层链式 null 检查 --> Optional + map() 巨型 switch-case 算法 --> 枚举策略 / 多态