Last Updated: February 25, 2016
· alexanderbrevig

Beware of Cyclomatic Complexity

<h3>Why should you care?</h3>
Because it will make you write maintainable code less prone to error.

<h3>What is cyclomatic complexity?</h3>
Cyclomatic complexity is a code metric. It is a number that corresponds to the total amount of execution paths through your code. This number is per method and is calculated like so:

  • start with 1 as count
  • for each branching keyword or operator add one to count

Keywords include if, for, while, case (not switch, count each keyword that represents a possible execution branch).
Operators include the ternary operator, and the null-coalescing/elvis operator if your language supports it. The below examples demonstrate a few languages and a branching operator (each example add one to count):

Person person = personArg ?? new Person(); //C#
var person = person || {}; //JavaScript
String name = g?.members?[0]?.name ?: "nobody"; //Java
int max = a >= b ? a : b; //C++

<h3>How can it help you?</h3>
I maintain a cyclomatic complecity count in my mind as I author code, and it makes it harder for me to author stupid code.

Every time I want to add a new execution branch I first explore other ways to accommodate the requirement (such as extending or appending to an existing if statement, or take care of the requirement in another location entirely).