2

Sonar Metrics 复杂性页面中,以下方法的复杂度为 5。

public void process(Car myCar){          <- +1
        if(myCar.isNotMine()){               <- +1
             return;                         <- +1
        }
        car.paint("red");
        car.changeWheel();
        while(car.hasGazol() && car.getDriver().isNotStressed()){   <- +2
             car.drive();
        }
        return;
    }

这是该工具计算复杂性的方式:

增加复杂性的关键字:if、for、while、case、catch、throw、return(这不是方法的最后一条语句)、&&、||、?

为什么case语句、if块和while块会增加方法的复杂性?这种方法复杂度的度量计算背后的直觉是什么?

4

3 回答 3

2

这是因为它们有条件增加了确保代码正确所需的测试数量

也可能ifs 的复杂性低于循环 ( while, for)。还阅读了与此相关的圈复杂度

阅读这篇博文,它描述了无法测试所有内容的实际情况以及测试所有内容所需的测试数量。

于 2013-03-06T17:41:42.597 回答
1

也许它是基于Cyclomatic ComplexityMcCabe 的(至少看起来像)。
该指标广泛用于软件工程领域。
看看这个:http ://en.wikipedia.org/wiki/Cyclomatic_complexity

于 2013-03-06T17:42:12.600 回答
1

Somar 测量圈复杂度,它表示通过源代码的线性独立路径的数量。

The key to answering your question comes from a research paper of Thomas McCabe, published in December of 1976:

It can be shown that the cyclomatic complexity of any structured program with only one entrance point and one exit point is equal to the number of decision points (i.e., 'if' statements or conditional loops) contained in that program plus one.

This is precisely what Sonar does: it finds the decision points, which come from loops, conditional statements, and multipart boolean expressions, and counts their number.

于 2013-03-06T17:47:36.153 回答