Java: Computing Cyclomatic Complexity

How to compute McCabe's Cyclomatic Complexity in Java methods

Flow complexity in methods. McCabe proposed a way to measuring flow complexity of a method which basically counts one for each place where the flow changes from a linear flow. His measurement was designed before exceptions and threads were used in programming languages, so what I've added I believe reflects some of the original intent. His algorithm, translated, at least approximately, into Java terms is as follows.

Keep complexity under 10

Lower is better. A McCabe complexity under 5 is good, from 5-10 is OK, and over 10 is too complex. A high flow complexity may be a symptom of a function which does too much or has low cohesion (does to many different things). But don't take these numbers too seriously -- you may have comprehensible control flow despite high numbers. For example, one large switch statement can be clear to understand, but can dramatically increase the count.

What to do about high complexity

Make simpler or break up complex methods. How do you simplify a method? Sometimes you can make a method simpler. Other times all program decisions have to be made, and you simplify it by breaking it into two or more methods. The complexity, the demands on the human to keep many things in their mind at the same time, can be reduced by breaking one method into two highly cohesive, well-named, methods.

External sources