We have this code, sortof:
private void InitializeEvents()
{
this.Event1 += (s,e) => { };
this.Event2 += (s,e) => { };
this.Event3 += (s,e) => { };
this.Event4 += (s,e) => { };
this.Event5 += (s,e) => { };
this.Event6 += (s,e) => { };
this.Event7 += (s,e) => { };
this.Event8 += (s,e) => { };
this.Event9 += (s,e) => { };
this.Event10 += (s,e) => { };
this.Event11 += (s,e) => { };
this.Event12 += (s,e) => { };
this.Event13 += (s,e) => { };
}
Code analysis in VS10 Ultimate says "cyclomatic complexity of 27". Removing one of the lines makes the cyclomatic complexity 25.
There's no branching going on, so how is this possible?
If a method has a cyclomatic complexity of 10, it means there are 10 independent paths through the method. This implies is that at least 10 test cases are needed to test all the different paths through the code. The lesser the number, the easier it is to test.
Consequences: A high cyclomatic complexity for a particular function means that the function will be difficult to understand, and more difficult to test. That in turn means functions with a cyclomatic complexity above 10 or 15 can be reasonably expected to have more undetected defects than simpler functions.
It is the Cyclomatic Complexity calculated based on the number of paths through the code. Whenever the control flow of a function splits, the complexity counter gets incremented by one. Each function has a minimum complexity of 1. This calculation varies slightly by language because keywords and functionalities do.
Remember that the Code Analysis is looking at the IL in your assembly, not your source code. There is nothing in the IL that natively supports lambda expressions, so they are a construct of the compiler. You can find the specifics of what is output here. But basically your lambda expression is turned into a private static class that is an anonymous delegate. However, rather that create an instance of the anonymous delegate every time it is referenced in code, the delegate is cached. So each time you assign a lambda expression, it does a check to see an instance of that lambda delegate has been created, if so it uses the cached delegate. That generates an if/else in the IL increasing the complexity by 2. So in this functions complexity is 1 + 2*(lambda express) = 1 + 2 *(13) = 27 which is the correct number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With