# Java: Complexity Measurement

Because complexity depends on many variable human characteristics, achieving automatic complexity measurement is probably hopeless. We are therefore left largely with a number of best practices which do a reasonable job of suggesting ways to avoid complexity.

## Flow Complexity

A major contribution to complexity (or simplicity) is the organization of program flow. Simplifying control flow was the prime motivation for Structured Programming, which can be summarized most simply, but not esspecially comprehensibly, as the elimination of the `goto` statement. The ideals of structured programming have been so completely incorporated in modern programming that some newer languages, eg Java, don't even have the `goto` statement. The Java designers must have thought leaving out `goto` was risky because `goto` is still reserved as a keyword, but is not used.

MacCabe proposed measuring flow complexity of a function (method) as the number of decision points. His algorithm is to count 1 for just entering the method, plus one for each if, for, while, do-while, case, &&, and ||. To update his measure for Java we should also add 1 for each ?: operator, catch statement, and default clause.

Break up complex methods. A MacCabe complexity under 5 is good, from 5-10 is ok, and over 10 is too complex. A high flow complexity may also be a symptom of a function which does too much and has low cohesion. But don't take these numbers too seriously -- you may have comprehensible control flow despite high numbers, eg generated by one large case statement. But how do you simplify a method? Presumably all decisions have to be made. You simplify a method by breaking it into two or more methods, so the complexity, the demands on the human to keep many things in their mind at the same time, are reduced.

## Other measures of complexity

There are many other measures of complexity: number of operators, number of lines of code, nesting depth, distance between variable references, etc.

## To Do

[When time permits I'll add links to some of the automated tools for measuring Java complexity.]