Cyclomatic Complexity

来自 SonarQube

函数的复杂度是通过函数体中的逻辑运算符(&&||)和条件控制语句(ifwhiledo-whilefor?:catchcasedefault)的数量来衡量的。

计算规则:

默认复杂度是 1,每遇到一次上述符号,复杂度增加 1。

  • 复杂度在 1 到 10 之间的方法被认为是简单的,易于理解和测试。
  • 复杂度在 10 到 20 之间的值表示代码更复杂,但仍然可以理解;然而,由于代码可能包含更多的分支,测试变得更加困难。
  • 复杂度在 20 及以上是典型的具有大量潜在执行路径的代码,只有经过极大的困难和努力才能完全掌握和测试。
  • 复杂度大于 50,肯定是不可维护的,或者说非常然维护的。

错误提示

  1. The Cyclomatic Complexity of this function is 31 which is greater than 20 authorized.
  2. The Cyclomatic Complexity of this function is 23 which is greater than 20 authorized.

分析

image-20260105153738910

其中:

  1. +1: function definition

    表示定义函数时,复杂度默认为 1。

  2. +1: if statement

    表示识别到 if 语句,复杂度加 1。

  3. +1: while loop

    表示识别到 whiledo-while 语句,复杂度加 1。

  4. +1: conditional operator

    表示识别到 ? : 语句,复杂度加 1。

  5. +1: logical operator

    表示识别到 &&||,复杂度加 1。

  6. +1: for loop

    表示识别到 for (;;) 语句,复杂度加 1。

测试

测试代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// value = 1
void cyclomatic_complexity_test(void)
{
    // value + 1 = 2
    while (1);

    // value + 1 = 3
    do {
        break;
    } while (1);

    // value + 1 = 4
    if (1) {
    }

    // value + 1 + 1 = 6
    if (true && true) {
    }

    // value + 1 + 1 + 1 + 1 = 10
    if ((true && true) || (false && false)) {
    }

    // value + 1 + 1 = 12
    if ((1 + 1) > 2 ? true : false) {
    }

    // value + 1 = 13
    if (1) {
    }

    // value + 1 = 14
    if (1) {
    }

    // value + 1 = 15
    if (1) {
    }

    // value + 1 = 16
    if (1) {
    }

    // value + 1 = 17
    if (1) {
    }

    // value + 1 = 18
    if (1) {
    }

    // value + 1 = 19
    if (1) {
    }

    // value + 1 = 20
    if (1) {
    }

    // value + 1 = 21
    if (1) {
    }
}

检查结果:

image-20260105162322188

image-20260105162413570

版权声明

本文为「Zeepunt 日常随笔」的原创文章,遵循 CC BY-NC-ND 4.0 许可协议。允许在署名作者、注明原文链接且不作任何更改的前提下非商业性地分享本文。

原文链接:https://zeepunt.github.io/article/code/sonarqubecyclomatic-complexity---%E5%9C%88%E5%A4%8D%E6%9D%82%E5%BA%A6/