This is done by directly measuring the number of paths through the code. Say a program is a graph of all possible operations. Then, complexity measures the number of unique paths through that graph. Every if, while, or for statement creates a new branch.
In 1976, Thomas McCabe Snr proposed a metric for calculating code complexity, called Cyclomatic Complexity. It's defined as: A quantitative measure of the number of linearly independent paths through a program's source code… computed using the control flow graph of the program.
Cyclomatic complexity (CYC) is a software metric used to determine the complexity of a program. It is a count of the number of decisions in the source code. The higher the count, the more complex the code.
Reduce the Number of Decision Structures You might consider this one a no-brainer. If the decision structures—especially if-else and switch case—are what cause more branches in the code, it stands to reason that you should reduce them if you want to keep cyclomatic complexity at bay.
While cyclomatic complexity is a worthwhile metric, I tend to find it to be a poor tool for identifying difficult to maintain code. In particular, I tend to find it just highlights certain types of code (e.g. parsers) and misses difficult recursion, threading and coupling problems as well as many of the anti-patterns that have been defined.
What other tools are available to identify problematic Java code ?
Note, we already use PMD and FindBugs which I believe are great for method level problem identification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With