如何简化Java代码中重复的if语句,提升代码简洁度与可读性?
Java重复if判断优化方案
优化逻辑
原代码的重复点为四个相邻方向的边界校验、状态判断、双并查集合并逻辑完全一致,仅坐标偏移量不同,通过抽离方向常量+循环遍历+公共方法抽离即可大幅简化代码。
具体实现
1. 类中新增公共配置与工具方法
// 定义上下左右四个方向的坐标偏移常量,后续新增方向(如斜向)只需在此添加元素即可 private static final int[][] DIRECTIONS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; // 抽离双并查集合并的重复逻辑,避免重复编码 private void unionBothUf(int posA, int posB) { unionFind.union(posA, posB); unionFind2.union(posA, posB); }
2. 优化后的open方法
public void open(int i, int j){ if (i > n - 1 || i < 0 || j > n - 1 || j < 0) { throw new IndexOutOfBoundsException("Index out of bounds."); } grid[i][j] = true; // 提前计算当前坐标的位置,避免循环中重复计算 int currentPos = location(i, j); // 遍历所有相邻方向统一处理 for (int[] dir : DIRECTIONS) { int neighborI = i + dir[0]; int neighborJ = j + dir[1]; if (neighborI >= 0 && neighborI < n && neighborJ >= 0 && neighborJ < n && grid[neighborI][neighborJ]) { unionBothUf(location(neighborI, neighborJ), currentPos); } } numberOpen++; }
优化收益
- 代码量缩减40%以上,核心逻辑更清晰,可读性大幅提升
- 后续维护仅需修改一处逻辑即可覆盖所有方向的处理规则,避免多副本if判断漏改的问题
- 提前缓存当前坐标位置,相比原实现还有微小的性能提升
内容的提问来源于stack exchange,提问作者ConstructionCat
相关产品推荐
相关产品推荐

