问题描述
我一直在努力学习如何降低圈复杂度。 我在这里的 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:封装条件。
布尔逻辑很难理解,无需在 if
或 while
语句的上下文中查看它。提取解释条件意图的函数。
例如:
if (shouldBeDeleted(timer))
优于
if (timer.hasExpired() && !timer.isRecurrent())
就像@tgdavies 建议提取一个函数一样:
if(shouldDoThatThing()) {
doThatThing();
} else {
doThisThing();
}
private boolean shouldDoThatThing() {
return something1() && something2() && something3() && something4() && something5();
}