if-else 多条件时的优化

有用。

当 if-else 需要判断的条件非常多的时候,可以考虑使用卫语句来提前把不符合条件的情况过滤出来。

就是把

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
if ($user != null) {
if (time() >= strtotime('12 pm')) {
if ($user->hasAccess(UserType.PREMIUM)) {
if ($store->hasItemsInStock()) {
// the content a premium user user should be able to see when the store is in stock
// after 12pm.
} else {
return 'We are completely sold out.';
}
} else {
return 'You do not have premium access to our website.';
}
} else {
return 'This section is not opened before 12PM';
}
} else {
return 'You are not signed in.';
}

改写成这种:

1
2
3
4
5
6
7
8
9
10
if (condition1()) {
return ...;
}

if (condition2()) {
return ...;
}

// Input is valid.
doSomething();

在《阿里巴巴 Java 开发手册(华山版)》的第一章《编程规约》也有提到:

【推荐】表达异常的分支时,少用if-else方式,这种方式可以改写成:

1
2
3
4
5
if (condition) {
...
return obj;
}
// 接着写else的业务逻辑代码;

说明:如果非使用if()…else if()…else…方式表达逻辑,避免后续代码维护困难,【强制】请勿超过3层。

正例:超过3层的 if-else 的逻辑判断代码可以使用卫语句、策略模式、状态模式等来实现,其中卫语句即代码逻辑先考虑失败、异常、中断、退出等直接返回的情况,以方法多个出口的方式,解决代码中判断分支嵌套的问题,这是逆向思维的体现。

示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void findBoyfriend(Man man) {
if (man.isUgly()) {
System.out.println("本姑娘是外貌协会的资深会员");
return;
}
if (man.isPoor()) {
System.out.println("贫贱夫妻百事哀");
return;
}
if (man.isBadTemper()) {
System.out.println("银河有多远,你就给我滚多远");
return;
}
System.out.println("可以先交往一段时间看看");
}

参考资料

  1. 别再用Else语句写代码了! - InfoQ
  2. Stop Using Else in Your Programs - Better Programming - Medium
  3. Guard (computer science) - Wikipedia)
  4. 阿里巴巴 Java 开发手册
  5. 优化代码中大量的if/else,你有什么方案? - 知乎