Java: 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.

• Add one for each of the following flow-related elements that are found in the method.
CategoryAdd 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, or continue.
Operators &&, ||, ?, and :
Exceptionscatch, finally, throw, or throws clause.

Example

Compute the cyclomatic complexity of the following `main` method.

 ``` 1* 2 3* 4 5 6 7 8 9** 10* 11 12 13 14 15 16* 17* 18 19 20 21 22 23* 24 25 26 27 ``` ```public static void main(String[] args) { init(); do { String prompt = "" + toHTML() + "
Enter row and column to bomb:"; //... Ask user for row and column input. String input = JOptionPane.showInputDialog(null, prompt); if (input == null || input.length() == 0) { break; // Quit if there is no input. } try { //... Split input into row and column. Sub 1 to get internal row/col String[] inputs = input.split(" "); if (inputs.length != 2) { throw new NumberFormatException(); } int row = Integer.parseInt(inputs[0]) - 1; int col = Integer.parseInt(inputs[1]) - 1; dropBomb(row, col); //... Drop bomb at those coords. } catch (NumberFormatException unused) { JOptionPane.showMessageDialog(null, "Enter two integers."); } } while (shipsRemain()); } ```

Each "*" beside a line number gets one point. This method is quite complicated.

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 too 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 will dramatically increase the count.

How to fix high complexity

Make simpler or break up complex methods. How do you simplify a method? Sometimes you can make a method simpler with a little more design thought, but often you will have to 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. This may seem counter-intuitive that creating another method will make something simpler, but if each method has a clear purpose, the result will be simpler.