Information Technology Reference
In-Depth Information
Reduce Code Complexity
Have you ever noticed that long methods are sometimes hard to fol-
low? Ever had trouble understanding the logic in an excessive, deeply
nested conditional? Your instincts are correct. Long methods and
methods with a high number of paths are hard to understand, and in
fact they actually have been shown to be directly proportionate with
defects.
A number of studies over time have shown a correlation between
the number of paths through code and defects. One metric that arose
from these studies is called the Cyclomatic Complexity Number
(CCN). The CCN is a plain integer that measures complexity by count-
ing the number of distinct paths through a method. Various studies
with this metric over the years have determined that methods with a
CCN greater than 10 have a higher risk of defects than other code of
the same bulk. 4
In Java, JavaNCSS 5 is an excellent tool that determines the lengths
of methods and classes by examining source files, and it also counts
the cyclomatic complexity of every method in a code base. By config-
uring JavaNCSS either through its Ant task or via a Maven plug-in, an
XML report is generated, which lists these data:
• The number of classes, methods, noncommenting lines of code,
and varying comment styles in each package
• The number of noncommenting lines of code, methods, inner
classes, and Javadoc comments in each class
• The total number of noncommenting lines of code and the cyclo-
matic complexity
JavaNCSS ships with a few style sheets that can generate an
HTML report summarizing the data. Figure 7-2 shows a sample
HTML report generated by Maven.
4. From www.sei.cmu.edu/str/descriptions/cyclomatic_body.html.
5. JavaNCSS is available at www.kclee.de/clemens/java/javancss/. CCMetrics
and Source Monitor provide CCN measurements for .NET.
 
Search WWH ::




Custom Search