Friday, September 6, 2013

What is cyclomatic complexity (C# testing interview questions with answers)?

Cyclomatic complexity helps you measure code complexity.  Higher the code complexity, more it is prone to errors and more important it becomes to unit test that specific code.

Cyclomatic complexity number depends on how many different execution paths your code can execute depending on varying inputs. More the code paths, more the complexity.

For example take the below code. There is nothing complex in the below code, we do not have many execution paths. We just have lots of code lines which does variable initialization.  So the cyclomatic complexity of the below code is “1”.

public void Cancel()
{
            Num1 = 0;
            Num2 = 0;
            Operation = "";
            Pie = 3.14;
            Num5 = 0;
            Operation1 = "";
            Num20 = 0;
            Numx = 0;
            OperationStart = "";
            PieMore = 3.145;
            Num6 = 0;
            Operationnew = "";
}

But now take the example of below code. There are 4 branch conditions in the below code as shown in the below table. So the cyclomatic complexity is “4”.


Input
Output
Path 1
Operation.Length ==0
Exception thrown
Path 2
Operation == “+”
Num1 + Num2
Path 3
Operation == “-“
Num1 – Num2
Path 4
Any other inputs
Num1 * Num2


public int Calculate()
        {
            if (Operation.Length == 0)
            {
                throw new Exception(" Operation not sepecified");
            }
                if (Operation == "+")
                {
                    return Num1 + Num2;
                }
                else if (Operation == "-")
                {
                    return Num1 - Num2;
                }
                else
                {
                    return Num2 * Num1;
                }
                return 0;

        }

To measure code complexity using visual studio , click on Analyze à Calculate code metric for the solution. This feature is available only for VS ultimate editions. Once done you should get the cyclomatic complexity as shown in the below figure. 




No comments: