How does a static dictionary have cyclic complexity?

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, analyzing Microsoft code means that it has a cyclical complexity of 27. I do not understand why a series of Add calls with delegates leads to such a high cyclic complexity.

What can I do to reduce cyclomatic complexity?

+4
source share
1 answer

I like this definition for CC - the amount of decision logic in a source code function (for more details see "Code metrics - cyclic complexity" , there is also a very good example of how CC is computed).

Since each Add() has two different code paths - Add() and Value , therefore CC+=2 . Since you put Add() 13 times - CC == at least 26 . And with regard to MSDN, the minimum CC is 2 , and when it increases, it starts to increase from 1, so you end with 27 :) Having an anonymous method in the dictionary value increases the complexity, since this could potentially cause an exception, so the test should also be covered.

Values โ€‹โ€‹of code indicators, MSDN :

Cyclomatic Complexity - Measures the structural complexity of a code. It is created by calculating the number of different code paths in the program stream. A program that has a complex control flow will require more tests to ensure good code coverage and less maintainability.


Just check what CC is 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); } 
+2
source

Source: https://habr.com/ru/post/1441301/


All Articles