圈复杂度路径数
Cyclomatic complexity paths count
我正在读一本关于可测试 JS 的书,其中有一章是关于 圈复杂度 ,但它并没有真正说明如何计算它。它只是说
Cyclomatic complexity is a measure of the number of independent paths through your code.
它给出了这个例子,说明它的圈复杂度为 2:
function sum(a, b) {
if (typeof(a) !== typeof(b)) {
throw new Error("Cannot sum different types!");
} else {
return a + b;
}
}
因此我想知道这个编造的例子的圈复杂度是否为 3:
function madeup(a) {
if (typeof(a) === "string") {
if (a === "some") {
console.log("is a some");
} else {
console.log("not a some");
}
} else {
console.log("not a string");
}
}
还有这 4 个:
function madeup(a) {
if (typeof(a) === "string") {
if (a === "some") {
console.log("is a some");
} else {
console.log("not a some");
}
} else {
if (a === 5) {
console.log("is a 5");
} else {
console.log("not a 5");
}
}
}
?
是的,你数对了。我想这就是所有可以说的了。
如果您不确定,可以将您的函数放入 http://jshint.com,它会告诉您什么是圈复杂度。
在第一个示例中,"throw new Exception" 和 RETURN 语句导致方法结束并且所有变量都超出范围。
第二个和第三个示例中的方法都在代码的最后一行之后终止。第二种和第三种方法只在一个地方,最后一行退出代码。
如果您在 console.log 方法之后有一个 RETURN 语句,那么您是正确的。
就目前而言,示例二和示例三的圈复杂度为 1。
我正在读一本关于可测试 JS 的书,其中有一章是关于 圈复杂度 ,但它并没有真正说明如何计算它。它只是说
Cyclomatic complexity is a measure of the number of independent paths through your code.
它给出了这个例子,说明它的圈复杂度为 2:
function sum(a, b) {
if (typeof(a) !== typeof(b)) {
throw new Error("Cannot sum different types!");
} else {
return a + b;
}
}
因此我想知道这个编造的例子的圈复杂度是否为 3:
function madeup(a) {
if (typeof(a) === "string") {
if (a === "some") {
console.log("is a some");
} else {
console.log("not a some");
}
} else {
console.log("not a string");
}
}
还有这 4 个:
function madeup(a) {
if (typeof(a) === "string") {
if (a === "some") {
console.log("is a some");
} else {
console.log("not a some");
}
} else {
if (a === 5) {
console.log("is a 5");
} else {
console.log("not a 5");
}
}
}
?
是的,你数对了。我想这就是所有可以说的了。
如果您不确定,可以将您的函数放入 http://jshint.com,它会告诉您什么是圈复杂度。
在第一个示例中,"throw new Exception" 和 RETURN 语句导致方法结束并且所有变量都超出范围。
第二个和第三个示例中的方法都在代码的最后一行之后终止。第二种和第三种方法只在一个地方,最后一行退出代码。
如果您在 console.log 方法之后有一个 RETURN 语句,那么您是正确的。
就目前而言,示例二和示例三的圈复杂度为 1。