【问题标题】:How does a static Dictionary have cyclomatic complexity?静态字典如何具有圈复杂度?
【发布时间】:2012-10-22 14:39:00
【问题描述】:

我有以下课程:

public static class MyClass
{
    private static readonly Dictionary<Type, Func<string, object>> valueTypes;

    static MyClass()
    {
        var dictionary = new Dictionary<Type, Func<string, object>>();
        dictionary.Add(typeof(bool), x => bool.Parse(x));
        dictionary.Add(typeof(byte), x => byte.Parse(x));
        dictionary.Add(typeof(char), x => char.Parse(x));
        dictionary.Add(typeof(decimal), x => decimal.Parse(x));
        dictionary.Add(typeof(double), x => double.Parse(x));
        dictionary.Add(typeof(float), x => float.Parse(x));
        dictionary.Add(typeof(int), x => int.Parse(x));
        dictionary.Add(typeof(long), x => long.Parse(x));
        dictionary.Add(typeof(sbyte), x => sbyte.Parse(x));
        dictionary.Add(typeof(short), x => short.Parse(x));
        dictionary.Add(typeof(uint), x => uint.Parse(x));
        dictionary.Add(typeof(ulong), x => ulong.Parse(x));
        dictionary.Add(typeof(ushort), x => ushort.Parse(x));
        MyClass.valueTypes = dictionary;
    }
}

但是,Microsoft 代码分析将此标记为具有 27 的圈复杂度。我不明白为什么一系列带有委托的 Add 调用会导致如此高的圈复杂度。

如何降低圈复杂度?

【问题讨论】:

  • Lambda 表达式就像一座冰山。语法糖很甜,但是这段代码在构造函数代码中创建了 13 个嵌套类和 26 个条件分支。查看它的唯一方法是按照分析工具的方式查看它,在程序集上运行 ildasm.exe。

标签: c#-4.0 cyclomatic-complexity


【解决方案1】:

我喜欢 CC 的这个定义 - the amount of decision logic in a source code function(更多信息请参见“Code Metrics – Cyclomatic Complexity”,还有一个很好的例子,CC 是如何计算的)。

所以因为每个Add() 都有两个不同的代码路径——Add() 本身和Value 函数,所以CC+=2。因为你把Add() 13 次-CC == 至少26。关于 MSDN,最小 CC 是 2,当它增加时,它从 1 开始增加,所以你最终得到 27 :) 在字典值中使用匿名方法会增加复杂性,因为它可能会引发异常,因此应该由也是一个测试。

Code Metrics Values, MSDN:

圈复杂度——衡量结构的复杂性 代码。它是通过计算不同代码路径的数量来创建的 在程序的流程中。具有复杂控制流的程序 将需要更多的测试来实现良好的代码覆盖率,并且会更少 可维护。


只是感兴趣的检查一下这些示例的 CC 是什么:

private static readonly Dictionary<Type, Func<string, object>> valueTypes
static MyClass()     
{         
    var dictionary = new Dictionary<Type, Func<string, object>>();         
    dictionary.Add(typeof(bool), x => bool.Parse(x)); 
}


static MyClass()     
{         
    var dictionary = new Dictionary<Type, Func<string, object>>();         
    Func<string, object> func = (x) => bool.Parse(x)
    dictionary.Add(typeof(bool), func); 
}

static MyClass()     
{         
    var dictionary = new Dictionary<Type, Func<string, object>>();         
    dictionary.Add(typeof(bool), null); 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 2020-06-13
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多