I have the following class:
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;
}
}
However, Microsoft Code Analysis flags this as having a cyclomatic complexity of 27. I do not understand why a series of Add calls with delegates results in such a high cyclomatic complexity.
What can I do to reduce the cyclomatic complexity?
I like this definition for CC - the amount of decision logic in a source code function
(See more on "Code Metrics – Cyclomatic Complexity", there is also very good example how is CC calculated).
So since each Add()
has two different code paths - Add()
itself and Value
function, so CC+=2
. Since you put Add()
13 times - CC ==
at least 26
. And regarding MSDN minimal CC is 2
and when it increased it start increasing from 1, so you ends up with 27 :) Having an anonymous method in a dictionary value increases a complexity since potentially it may raise an exception so should be covered by a test as well.
Code Metrics Values, MSDN:
Cyclomatic Complexity – Measures the structural complexity of the
code. It is created by calculating the number of different code paths
in the flow of the program. A program that has complex control flow
will require more tests to achieve good code coverage and will be less
maintainable.
Just of interest check what are CC for these examples:
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);
}