


All the lines will be run, every time the function is called. However, it also has only one path through it. IncreaseSalary_Long has more lines of code than IncreaseSalary_Short. Every call to that function will run the one line in it. The IncreaseSalary_Short function has one possible execution path through it. Salary = Salary * (1 + ((increasePercentage / 2) / 100)) People employed 90-179 days can only receive a half increase People employed more than 180 days can receive a full increase TimeSpan timeEmployed = DateTime.Now - HireDate Public void IncreaseSalary_Complex(decimal increasePercentage) Return IsStillEmployed ? "Active" : "Former" Public void IncreaseSalary_Long(decimal increasePercentage)ĭecimal percent = increasePercentage / 100 Salary = Salary * (1 + (increasePercentage / 100)) Public void IncreaseSalary_Short(decimal increasePercentage) You can do this by counting the number of conditional statements (“if”, “else”, and “case”), and adding 1 (the “default” path through the function). To manually determine a function’s cyclomatic complexity, you need to count each potential branch through it. I’ll use this Employee class to demonstrate.

How to manually measure Cyclomatic Complexity However, that might also be the simplest way to write that function. A “switch” statement with many “case” options would have a high CC.

NOTE: An important thing to remember is that cyclomatic complexity is only an indicator of a possible problem. So, when I see a function with a CC over 30, I start to look for ways to simplify it, or to break it into smaller functions. And, if I don’t understand what a function is doing, it is extremely difficult to fix bugs in it, or modify it. In my experience, code with high cyclomatic complexity is usually the code with the most bugs. If a function has a CC of more than around 30, it starts to become difficult to understand what it is doing – at least, it usually does for me. This gives you an approximate idea of how complex a function is – more possible paths, equals more complex.Ī computer does not have a problem running a function with 100+ paths through it. produces another potential path through a function, and increases the cyclomatic complexity count by 1. So, it has a cyclomatic complexity of 1.Įach “if”, “else”, “case”, etc. If a function does not have any conditional statements (“if”, “else”, “case”, etc.), there is only one possible path through the function. Cyclomatic Complexity (I’ll use “CC”, to abbreviate it, in places) is the number of potential execution paths (codepaths) that exist in a function.
