Wednesday, May 30, 2012

Cyclomatic Complexity

Cyclomatic complexity is about how complex the code is written. Too many conditional statements and lengthier methods add to the complexity of the method. Complexity is measured as an integer number. Lets say a method's code complexity is 8, there have to 8 unit test cases written for it.An 'if' condition leads to the complexity of 2. 1 for if statement and another for else case. Software code with high complexity is more difficult for a programmer to understand because programmer has to understand different pathways and results of those pathways. The changes of bugs are high in high complexity code. Also chances of regression bugs are high in high complexity modules. These conditional complexity is referred as Cyclomatic Complexity.

Complexity Levels

Complexity
The Risk Factor
01 - 10
Simple program without much risk
11 – 20
More complex, Moderate risk
21 – 59
Complex, high risk program
Greater than 50
Untestable Code

How to calculate the complexity?

Code complexity can be calculated manually. For example counting number of closed loops, 2 for if conditions, 1 for switch statements etc but it is tedious job. There are tools which can calculate the complexity. In eclipse IDE, metrics plugin can be downloaded and installed. Find the complete procedure for calculating and viewing the results in eclipse IDE at http://metrics.sourceforge.net/

One of the objectives of code review is to look for the code complexity. Having the first complexity level increases the code readability. Readability is important because in a software life time, 80% the code is 'read' and only 20% of the time code is written. When the software goes under maintenance phase, the code only read and very minimal changes are done on top of existing code. 'Write code as if you are writing a story' so that people reading the code can understand it in less time and go home early!

Legacy code complexity can be reduced by refactoring the code

You might be interested on this article. Code improvement through Cyclomatic Complexity.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...