【问题标题】:Sonar doesn't increment cyclomatic complexity score for 'forEach' loops in java声纳不会增加 java 中“forEach”循环的圈复杂度分数
【发布时间】:2020-04-14 15:26:42
【问题描述】:

假设我有以下代码。

map.forEach((key, value) -> { //No Sonar cyclomatic complexity score

  for (String s : value) {   //Sonar lint : +2 (including 1 for nesting) 
    if (condition) {...}     //Sonar lint : +3 (including 2 for nesting)
  }

}

如上所述,对于 for 循环,Sonar 的得分为 2,同时考虑了线性结构破坏和嵌套这两个事实。这完全没问题。

map.forEach((key, value) -> { //No Sonar cyclomatic complexity score

  value.forEach(s-> {        //No Sonar cyclomatic complexity score
    if (condition) {...}     //Sonar lint : +3 (including 2 for nesting)
  }); 

}

但是,如果我如上所述为 forEach 循环重构 for 循环,那么所有关于 for 循环的圈复杂性的 Sonar 投诉将离开。但正如您所见,对于 if 语句的圈复杂度是相同的。这意味着对于 if 语句,Sonar 认为嵌套的分数相同(分数为 2),这意味着它嵌套在下面 2 层(因为它在两个 forEach 语句下)。

我的问题是,Sonar 在结构和嵌套方面都没有计算 forEach 循环的圈复杂度背后的逻辑是什么,尽管它已经计算了 if 的结构和嵌套圈复杂度em> 声明。这是正确的还是 SonarLint 插件中的一些错误?

【问题讨论】:

    标签: java sonarlint cyclomatic-complexity


    【解决方案1】:

    方法(或构造函数)的圈复杂度是个数 通过该方法的可能的线性无关执行路径 (参见[维基百科])。它最初是作为复杂性引入的 由 Thomas McCabe [McCabe] 测量。

    这与 for-each 与 for-loop 无关,这只是因为 lambda 表达式,lambda 表达式使其成为匿名方法调用,因此它不被视为方法的圈复杂度,因为它成为线性路径你的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-11
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多