A measure of how complex a section of code is. Stands for the number of unique paths that can be taken through said code. Also gives an upper limit on the number of test cases that must be written to fully test that code.

Can grow quite quicky and easily, often to unmanageable proportions. Ten is often considered a good maximum to allow maintainable code.

A quote from Edmond VanDoren of the Software Engineering Institute at Carnegie Mellon University:
A low cyclomatic complexity contributes to a program's understandability and indicates it is amenable to modification at lower risk than a more complex program. A module's cyclomatic complexity is also a strong indicator of its testability.

I saw one function at work with a complexity of 237. Scary.

Cyclomatic Complexity is a metric, and is the work of Mr McCabe. It tells us how complex a piece of code is in terms of the number of linearly different paths through that code. Although the cyclomatic complexity does give a good indicator of how many tests will be sufficient to test the code, it is sometimes misleading as an indicator of complexity.

Each decision in the code increases the complexity, with no reference to how deeply nested (and therefore 'hard' for a human to understand and maintain) those decisions are. A module with a high cyclomatic complexity may merely have a large number of decisions which are not nested. For example, a module containing a very long list of
   if (foo) then (bar)
would be a doddle to understand and maintain, and so not as complex as its cyclomatic complexity metric would lead us to believe.

Anyway. How it works

Imagine that this horrible piece of ascii art is graph, G


+-------+
|       |
+-------+       
    |           
    |           
   / \          
  /   \         
 <     >--------|     
  \   /        / \ 
   \ /        /   \
    |        <     >--
    |         \   /  |
    |---       \ /   |
       |        |    |
       |        |    |
      a|      b |    |c
       |        |    |
    +-------+  +-------+
    |       |  |       |
    +-------+  +-------+
           |     |
           |     |
          +-------+
          |       |
          +-------+

The cyclomatic complexity, v(G) is number of independent paths through graph, G. You can see them, labelled a, b and c, in the diagram.

v(G) = e - n + 2 where
e = edges (here, 7 - the lines) and
n = nodes (here, 6 - all the boxes)

v(G) = 7 - 6 + 2
= 3

v(G) can, however, be expressed more simply.

v(G) = d + 1 where
d = decision nodes (here, 2 - just the diamond(ish) shaped boxes)

v(G) = 2 + 1
= 3

And there we have it. Add one to the number of decision nodes. Cyclomatic complexity is a static metric, it does not require the code to be executed. If you are interested in how many of these paths have been executed (for example, to determine testing effectiveness) then you'll want to know about the dynamic metric of code coverage.

Log in or register to write something here or to contact authors.