Coding: A small note on Cyclomatic complexity

One way of deriving a measure of complexity is by means of the Cyclomatic complexity. This measure was introduced by Thomas McCabe in 1976. This basically treats the programs structure as a graph. What is a graph? Similar in many respects to a flow chart, a graph has nodes (actions), and edges (program flow between actions). If E is the number of edges, and N the number of nodes, and P is the number of connected components (for a single piece of code P is equal to 1) the cyclomatic complexity can be derived using:

C = E – N + 2P

Consider the following program segment, and associated cyclomatic graph:


In this case the number of nodes is 8, the number of edges 9, C=9-8+(2*1) = 3. Works nice for a small program, but I hate to think what a large piece of code would look like!

McCabe, T.J., “A complexity measure”, IEEE Trans. on Software Engineering, SE-2(4), pp.308-320 (1976)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s