【发布时间】:2013-07-29 11:12:46
【问题描述】:
每当我对正在处理的一段代码进行 lint 处理时,我都会得到 This function's cyclomatic complexity is too high. (7)。但我有点困惑如何以这种方式重写它以使其正常工作。
这将是不断抛出该消息的函数:
function () {
var duration = +new Date() - start.time,
isPastHalf = Number(duration) < 250 && Math.abs(delta.x) > 20 || Math.abs(delta.x) > viewport / 2,
direction = delta.x < 0;
if (!isScrolling) {
if (isPastHalf) {
if (direction) {
this.close();
} else {
if (this.content.getBoundingClientRect().left > viewport / 2 && pulled === true) {
this.close();
return;
}
this.open();
}
} else {
if (this.content.getBoundingClientRect().left > viewport / 2) {
if (this.isEmpty(delta) || delta.x > 0) {
this.close();
return;
}
this.open();
return;
}
this.close();
}
}
}
我想听听一些关于如何以这种方式构造我的代码以避免这种情况的建议。
【问题讨论】:
-
是什么导致了这个错误?
-
认真的吗?不要使用嵌套的
ifs。根据单一职责原则分解职责。一段代码(一个模块)应该只做一件事,而且它应该做得很好。想想这些丑陋的 if-bushes 生成了多少可能的执行路径...... -
你读过代码@Powerslave吗?这如何破坏 SRP?
-
一些谷歌搜索显示这是特定于
jshint,因此您应该相应地标记您的问题。 -
您可以考虑在codereview.stackexchange.com上发布此类问题
标签: javascript jshint cyclomatic-complexity