4

我有以下课程:

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 调用会导致如此高的圈复杂度。

我能做些什么来降低圈复杂度?

4

1 回答 1

2

我喜欢 CC 的这个定义—— the amount of decision logic in a source code function(参见“代码度量 – 圈复杂度”的更多信息,还有一个很好的例子,CC 是如何计算的)。

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

代码度量值,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); 
}
于 2012-10-22T14:51:40.463 回答