2012-10-22 27 views
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; 
    } 
} 

然而,微軟的代碼分析其標記爲具有27圈複雜,我不明白爲什麼一個系列添加在如此高的圈複雜度代表結果的呼叫。

我該怎麼做才能減少圈複雜度?

+0

見http://stackoverflow.com/questions/10244131/how-can-the-cyclomatic-complexity-be -27-in-a-method-with-13-event-handler-subscr – cm007

+1

Lambda表達式就像一座冰山一樣。語法糖非常甜,但是此代碼在構造函數代碼中創建了13個嵌套類和26個條件分支。要看到它的唯一方法是以分析工具的方式來查看它,在程序集上運行ildasm.exe。 –

回答

2

我喜歡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); 
}