如何降低if中多个条件的圈复杂度?

问题描述

我一直在努力学习如何降低圈复杂度。 我在这里的 if 语句中有 5 个或更多条件检查,例如

if(something1() && something2() && something3() && something4() && something5()){
     doThatThing();
}else{
     doThisThing();
}

上述代码段的圈复杂度为 6(5 条件 +1 if)。 我知道使用 Enum责任链 来重构多个 if else。 但是,这里我只有 1 个 if else 条件可以很多。

如何重构上述代码以降低圈复杂度,因为在实际场景中我最多可能有 7 个条件。

解决方法

根据 Clean Code by Robert C. Martin,第 301 页,这是一种普遍的气味:

G28:封装条件
布尔逻辑很难理解,无需在 ifwhile 语句的上下文中查看它。提取解释条件意图的函数。
例如:

if (shouldBeDeleted(timer))

优于

if (timer.hasExpired() && !timer.isRecurrent())

就像@tgdavies 建议提取一个函数一样:

if(shouldDoThatThing()) {
  doThatThing();
} else {
  doThisThing();
}

private boolean shouldDoThatThing() {
  return something1() && something2() && something3() && something4() && something5();
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...