Tuesday 3 July 2007

An easy way to improve code quality

Cyclomatic Complexity has been around for a long time and yet many developers are still unaware of it. Cyclomatic Complexity is the measure of code complexity. It's just one aspect of code quality but I've found it's impact to be massive when used daily within the software development life cycle. Cyclomatic Complexity Analysis basically counts the number of decision points (e.g. If's, elseif's, Case's, nesting levels, etc) in source code and gives you a rating. These ratings can be assessed as follows:

Cyclomatic ComplexityRisk Evaluation
1-10a simple program, without much risk
11-20more complex, moderate risk
21-50complex, high risk program
greater than 50untestable program (very high risk)

The reality is that the most complex areas of a code base attract the most bugs and as it's complex code it's harder to fix (and costs more!).

About 3 months ago I introduced it into the daily build on all projects at my company so that the build fails if code is introduced into the build with a complexity rating greater than 15. Initially it took a while for the development team (34 developers) to make it part of their daily routine but it has paid massive dividends. We've noticed a sharp decrease in the number of bugs found in the testing phase, and maintenance of the code base's have eased dramatically.

If a developer can't get the complexity down below 15 then it's put out for review to other developers. There are occasions when it's truly not possible to reduce the complexity due to performance tradeoffs but at least those important decisions are being handled in the correct manor.

Out of curiosity I ran the analysis tool over some past projects to get a feel for some kind of baseline to measure improvements against. One particular project reported a maximum complexity of 536!! I thought the analysis tool was broken until I dove into the source code and found a single method containing over 3000 lines of code, consisting mainly of if, elseif, if, elseif, etc. Also, the deepest level of nesting in this method was 24! Only a complete nutter could have written this!

So in summary, my advice to you as a developer is anything you write, analyse the complexity and simplify accordingly.

There are many other tools available for analysing code complexity such as IDE integrated plugins from Developer Express to name just one. Find the one that's right for you and use it.

The best tool I found for analysing complexity is Source Monitor. It's good for two reasons; you can run it as part of your daily build & smoke test, and it's free! It works with all the mainstream languages such as C#, VB.NET, Java, and we've also managed to get it to work with Actionscript 2.0.

1 comment:

Anonymous said...

Well written article.