At work we are looking into common problems that lead to high cyclomatic complexity. For example, having a large if-else statement can lead to high cyclomatic complexity, but can be resolved by replacing conditionals with polymorphism. What other examples have you found?
-
Any construct that has branching behaviour increases cyclomatic complexity – Mitch Wheat Feb 02 '10 at 16:33
-
http://en.wikipedia.org/wiki/Cyclomatic_complexity: – Mitch Wheat Feb 02 '10 at 16:34
-
You say "cyclomatic complexity" like it's an inherently bad thing. Wouldn't you do better by looking at what causes actual problems? – David Thornley Feb 02 '10 at 16:39
-
Yes we know what cc is - and a good practise is to make sure the cc isn't high otherwise you increase your risk of introducing new errors when trying to debug errors that region because it is overly complicated. There are common poor practises that lead to these undesirable high levels of cc - like big if else statements, I was wondering if others have encountered other poor practises leading to undersiably high levels. – Daniel Feb 02 '10 at 17:06
2 Answers
See the NDepend's definition of Cyclomatic Complexity.
Nesting Depth is also a great code metric.
Cyclomatic complexity is a popular procedural software metric equal to the number of decisions that can be taken in a procedure. Concretely, in C# the CC of a method is 1 + {the number of following expressions found in the body of the method}:
if | while | for | foreach | case | default | continue | goto | && | || | catch | ternary operator ?: | ??
Following expressions are not counted for CC computation:
else | do | switch | try | using | throw | finally | return | object creation | method call | field access
Adapted to the OO world, this metric is defined both on methods and classes/structures (as the sum of its methods CC). Notice that the CC of an anonymous method is not counted when computing the CC of its outer method.
Recommendations: Methods where CC is higher than 15 are hard to understand and maintain. Methods where CC is higher than 30 are extremely complex and should be split in smaller methods (except if they are automatically generated by a tool).

- 13,237
- 6
- 61
- 92
Another example to avoid using so many if´s, it's the implementation of a Finite State Machine. Because events fire transitions, so the conditionals are implicit in a clearer way with these transitions that changes the state of the System. The control is easier.
Leave you a link where mentions some of it´s benefits:
http://www.skorks.com/2011/09/why-developers-never-use-state-machines/

- 1,479
- 17
- 26