【发布时间】:2018-05-03 12:37:59
【问题描述】:
我有一些嵌套的 if/else 语句,但我想减少它们的开销。
在示例中,我正在评估从哪个下拉列表中单击了 li 项,以及该 li 项是否是第一个 (currentIndex === 0)。
代码:
if (parentIndex === 1) {
// But its own index is 0
if (currentIndex === 0) {
parentIndex = 2;
updatedIndexPos = array[1];
mainIndex =list_2.indexOf(updatedIndexPos);
// If the previous line is -1:
if (mainIndex === -1) {
parentIndex = 1;
updatedIndexPos = filterIndexPos;
mainIndex = list_1.indexOf(updatedIndexPos);
}
} else {
mainIndex = list_1.indexOf(mainIndexPos);
}
} else if (parentIndex === 2) {
// But its own index is 0
if (currentIndex === 0) {
parentIndex = 1;
updatedIndexPos = array[0];
mainIndex = list_1.indexOf(updatedIndexPos);
// If the previous line is -1:
if (mainIndex === -1) {
parentIndex = 2;
updatedIndexPos = filterIndexPos;
mainIndex = list_2.indexOf(updatedIndexPos);
}
} else {
mainIndex = list_2.indexOf(mainIndexPos);
}
}
看着它有很多重用的代码,而 eslint 给了我 7 的复杂度。我已经尝试将它分解成更小的函数并传递参数,但仍然没有设法解决这个代码块的复杂性。
【问题讨论】:
-
说明代码应该做什么是一个开始。
-
由于您的代码可以工作,但您正在寻找具体的改进,我建议将其发布到Code Review,该地址的存在是为了审查和改进工作代码。请阅读他们的How to Ask a Good Question,因为它与 Stack Overflow 有所不同。
-
如果您也在使用类似 React 的框架,请尝试阅读状态机示例 blog.markshead.com/869/state-machines-computer-science,它会为您提供很多想法并很好地添加到您的工具集中。
-
这部分函数的 eslint 返回复杂度为 7。代码审查通过的复杂度为 6 或更低,所以我想尽可能减少这部分。它在真正意义上并不复杂,但按照 linting 标准它是
-
好的,让我重新表述一下该评论。 The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or at least most of it) in programming. “应该” 6 时随机得分为 7 是过早的优化。循环复杂度是衡量代码质量的一个有缺陷的指标。
标签: javascript jquery if-statement cyclomatic-complexity