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 andValue
function, soCC+=2
. Since you putAdd()
13 times -CC ==
at least26
. And regarding MSDN minimal CC is2
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:
Just of interest check what are CC for these examples: