One of the key metrics of software quality is cyclomatic complexity. It gives an idea of the number of tests needed to cover all the code in a method (the number of “execution paths”), which often correlates inversely with the readability and maintainability of the code (i.e. lower is better). There are a lot of tools which calculate it for you.

But did you know that McCabe’s formula for cyclomatic complexity is basically the same as Euler’s formula to calculate the number of faces of a polyhedron?

For calculating cyclomatic complexity, each statement in the code is considered a vertex in a graph, and an edge in the graph is added from that vertex to each possible statement which could follow it (including the implicit return if there isn’t an explicit one). Thus an *if* statement is a vertex with 2 outgoing edges (the true case and the false case), for example.

Where E and V are respectively the number of edges and the number of vertices:

Complexity = E – V + 2

In Euler’s formula, rearranged, the number of faces F = E – V + 2, which is the same as the formula for cyclomatic complexity.

So that really ugly legacy method you’d rather not have to modify might actually be a dodecahedron…

*Digression: My browser’s spell-checker suggested for this post the title “Is your code a rhododendron?”. If you have ever written or seen rhododendron-like code, please leave a comment about it. 🙂*