Being new at work, our team took a while before we placed our code on the standard build system (just conventions on where to place codes, reports, etc). One of the tools in the build system is checkstyle. Since we were trying to roll-out a working prototype, we had received some nasty violations from this system. Among those violations is having a cyclomatic complexity above the threshold (it was my code). My code was doing some list processing so it was rich with conditional branches and loops. I reasoned out that we should take it as a warning instead of an error (as checkstyle does) or a flag that the code “might” be improved further and not consider it as an outright violation. There are just some code that cannot be written in any other way.
I always have problems with metrics. Most of the time they are not well understood and you just have this tool that calculates it for you and a rule of thumb that says : “everything above this is bad/good”. Just in case I have this perfectly good code that violates our cyclomatic complexity threshold, I better understand it.
Cyclomatic complexity is metric that measures how complex a program is. Computing cyclomatic complexity involves modelling your program as graph. Vertices are the statements and the edges are the flow from one statement to another. Cyclomatic complexity is then computed as the number of edges minus the number of nodes plus two times the number of connected components. If you are not into graph theory, a simpler way to compute this is to count the number of conditional statements inside ifs and loops plus one.
As an example, I fed the code below to checkstyle and I got a cyclomatic complexity of 7. It’s a simple code right? If I add more colors (and consequently the score will increase by the number of colors I add to it), it would still be simple right?
public static final int WHITE = 0;
public static final int BLACK = 1;
public static final int RED = 2;
public static final int BLUE = 3;
public static final int GREEN = 4;
public static final int YELLOW = 5;
public String getColor(int colorCode) {
switch(colorCode) {
case WHITE:
return "white";
case BLACK:
return "black";
case RED:
return "red";
case BLUE:
return "blue";
case GREEN:
return "green";
case YELLOW:
return "yellow";
default:
throw new RuntimeException("Invalid color!");
}
}
————————————————–
P.S. The cyclomatic complexity violation of my code was fixed when I removed some code duplication and pushed some of my code on a different method.
*Measurbator is a term coined by Ken Rockwell in Seven Levels of Photographers. A measurbator is someone who pixel-peeps and care more about their gears than take photographs.





