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.
- Start with a count of one for the method.
- Add one for each of the following flow-related elements that are found in the method.
Category Add one for each of the following Returns Each return that isn't the last statement of a method. Selection if, else, case, default. Loops for, while, do-while, break, and continue. Operators &&, ||, ?, and : Exceptions catch, finally, throw, or throws clause.
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
- See Cyclomatic Complexity for a typical description in terms of flow graphs.
- Wikipedia is also a good source: Cyclomatic complexity .
- There's a Java program that reads your .jar files and displays the size and cylclomatic complexity of each method. See CyVis Software Complexity Visualizer.