## Thursday, February 12, 2009

### Cyclomatic Complexity Much of my day is spent convincing engineers that there are simpler ways of implementing their designs. Much of the rest is convincing executives and managers that what they want isn't simple at all.

Invariably some little hot-head tries to argue with me that implementing a general case is more complicated than a special optimized case. If the punk in question has cracked a book they'll likely bring up some metric like Cyclomatic Complexity.

Thomas McCabe socialized this metric in the 70's as a mechanism for predicting where code would have future maintain problems. It's often thrown into the blender when people are trying to construct qualitative measures for code quality. Here's the formal equation:

CC = E - N + P

E = number of edges N = number of nodes P = number of connections or exits

It can be hard to see how equations like this apply to code so let me say it a different way: Cyclomatic Complexity represents the number of code paths through a section code.

How do you count the code paths? Start with one for the entry into the code, and add one more for every decision point. Decision points are the control of flow statements like If…Then…Else or Switch. The CC for the following snippet is three (3).

public int adjustRange( int rangePrimary ) {
if ( rangePrimary == 6 ) {