Class JavaMetrics

  • public final class JavaMetrics
    extends Object
    Built-in Java metrics. See Metric and MetricsUtil for usage doc.
    See Also:
    "Michele Lanza and Radu Marinescu. Object-Oriented Metrics in Practice: Using Software Metrics to Characterize, Evaluate, and Improve the Design of Object-Oriented Systems. Springer, Berlin, 1 edition, October 2006."
    • Field Detail


        public static final Metric<JavaNode,​Integer> ACCESS_TO_FOREIGN_DATA
        Number of usages of foreign attributes, both directly and through accessors. "Foreign" hier means "not belonging to this", although field accesses to fields declared in the enclosing class are not considered foreign.

        High values of ATFD (> 3 for an operation) may suggest that the class or operation breaks encapsulation by relying on the internal representation of the classes it uses instead of the services they provide.

      • CYCLO

        public static final Metric<ASTMethodOrConstructorDeclaration,​Integer> CYCLO
        Number of independent paths through a block of code. Formally, given that the control flow graph of the block has n vertices, e edges and p connected components, the cyclomatic complexity of the block is given by CYCLO = e - n + 2p. In practice it can be calculated by counting control flow statements following the standard rules given below.

        The standard version of the metric complies with McCabe’s original definition:

        • Methods have a base complexity of 1.
        • +1 for every control flow statement (if, case, catch, throw, do, while, for, break, continue) and conditional expression (?:). Notice switch cases count as one, but not the switch itself: the point is that a switch should have the same complexity value as the equivalent series of if statements.
        • else, finally and default do not count;
        • +1 for every boolean operator (&&, ||) in the guard condition of a control flow statement. That’s because Java has short-circuit evaluation semantics for boolean operators, which makes every boolean operator kind of a control flow statement in itself.

        Code example:

         class Foo {
           void baseCyclo() {                // Cyclo = 1
           void highCyclo() {                // Cyclo = 10
             int x = 0, y = 2;
             boolean a = false, b = true;
             if (a && (y == 1 ? b : true)) { // +3
               if (y == x) {                 // +1
                 while (true) {              // +1
                   if (x++ < 20) {           // +1
                     break;                  // +1
               } else if (y == t && !d) {    // +2
                 x = a ? y : x;              // +1
               } else {
                 x = 2;
        See Also:

        public static final Metric<ASTMethodOrConstructorDeclaration,​Integer> COGNITIVE_COMPLEXITY
        Cognitive complexity is a measure of how difficult it is for humans to read and understand a method. Code that contains a break in the control flow is more complex, whereas the use of language shorthands doesn't increase the level of complexity. Nested control flows can make a method more difficult to understand, with each additional nesting of the control flow leading to an increase in cognitive complexity.

        Information about Cognitive complexity can be found in the original paper here: CognitiveComplexity

        Basic Idea

        1. Ignore structures that allow multiple statements to be readably shorthanded into one
        2. Increment (add one) for each break in the linear flow of the code
        3. Increment when flow-breaking structures are nested


        There is an increment for each of the following:
        • `if`, `else if`, `else`, ternary operator
        • `switch`
        • `for`, `foreach`
        • `while`, `do while`
        • `catch`
        • `goto LABEL`, `break LABEL`, `continue LABEL`
        • sequences of binary logical operators
        • each method in a recursion cycle

        Nesting level

        The following structures increment the nesting level:
        • `if`, `else if`, `else`, ternary operator
        • `switch`
        • `for`, `foreach`
        • `while`, `do while`
        • `catch`
        • nested methods and method-like structures such as lambdas

        Nesting increments

        The following structures receive a nesting increment commensurate with their nested depth inside nested structures:
        • `if`, ternary operator
        • `switch`
        • `for`, `foreach`
        • `while`, `do while`
        • `catch`

        Code example

         class Foo {
           void myMethod () {
             try {
               if (condition1) { // +1
                 for (int i = 0; i < 10; i++) { // +2 (nesting=1)
                   while (condition2) { } // +3 (nesting=2)
             } catch (ExcepType1 | ExcepType2 e) { // +1
               if (condition2) { } // +2 (nesting=1)
           } // Cognitive Complexity 9
      • FAN_OUT

        public static final Metric<JavaNode,​Integer> FAN_OUT
        This counts the number of other classes a given class or operation relies on. Classes from the package java.lang are ignored by default (can be changed via options). Also primitives are not included into the count.

        Code example:

         import java.util.*;
         public class Foo { // total 8
             public Set set = new HashSet(); // +2
             public Map map = new HashMap(); // +2
             public String string = ""; // from java.lang -> does not count by default
             public Double number = 0.0; // from java.lang -> does not count by default
             public int[] intArray = new int[3]; // primitive -> does not count
             \@Deprecated // from java.lang -> does not count by default
             public void foo(List list) throws Exception { // +1 (Exception is from java.lang)
                 throw new IOException(); // +1
             public int getMapSize() {
                 return map.size(); // +1 because it uses the Class from the 'map' field
        See Also:

        public static final Metric<JavaNode,​Integer> LINES_OF_CODE
        Simply counts the number of lines of code the operation or class takes up in the source. This metric doesn’t discount comments or blank lines. See NCSS for a less biased metric.
      • NCSS

        public static final Metric<JavaNode,​Integer> NCSS
        Number of statements in a class or operation. That’s roughly equivalent to counting the number of semicolons and opening braces in the program. Comments and blank lines are ignored, and statements spread on multiple lines count as only one (e.g. int\n a; counts a single statement).

        The standard version of the metric is based off [JavaNCSS](

        • +1 for any of the following statements: if, else, while, do, for, switch, break, continue, return, throw, synchronized, catch, finally.
        • +1 for each assignment, variable declaration (except for loop initializers) or statement expression. We count variables declared on the same line (e.g. int a, b, c;) as a single statement.
        • Contrary to Sonarqube, but as JavaNCSS, we count type declarations (class, interface, enum, annotation), and method and field declarations.
        • Contrary to JavaNCSS, but as Sonarqube, we do not count package declaration and import declarations as statements. This makes it easier to compare nested classes to outer classes. Besides, it makes for class metric results that actually represent the size of the class and not of the file. If you don’t like that behaviour, use the JavaMetrics.NcssOption.COUNT_IMPORTS option.
         import java.util.Collections;       // +0
         import;         // +0
         class Foo {                         // +1, total Ncss = 12
           public void bigMethod()           // +1
               throws IOException {
             int x = 0, y = 2;               // +1
             boolean a = false, b = true;    // +1
             if (a || b) {                   // +1
               try {                         // +1
                 do {                        // +1
                   x += 2;                   // +1
                 } while (x < 12);
                 System.exit(0);             // +1
               } catch (IOException ioe) {   // +1
                 throw new PatheticFailException(ioe); // +1
             } else {
               assert false;                 // +1
      • NPATH

        public static final Metric<ASTMethodOrConstructorDeclaration,​BigInteger> NPATH
        Number of acyclic execution paths through a piece of code. This is related to cyclomatic complexity, but the two metrics don’t count the same thing: NPath counts the number of distinct full paths from the beginning to the end of the method, while Cyclo only counts the number of decision points. NPath is not computed as simply as CYCLO. With NPath, two decision points appearing sequentially have their complexity multiplied.

        The fact that NPath multiplies the complexity of statements makes it grow exponentially: 10 if .. else statements in a row would give an NPath of 1024, while Cyclo would evaluate to 20. Methods with an NPath complexity over 200 are generally considered too complex.

        We compute NPath recursively, with the following set of rules:

        • An empty block has a complexity of 1.
        • The complexity of a block is the product of the NPath complexity of its statements, calculated as follows:
          • The complexity of for, do and while statements is 1, plus the complexity of the block, plus the complexity of the guard condition.
          • The complexity of a cascading if statement (if .. else if ..) is the number of if statements in the chain, plus the complexity of their guard condition, plus the complexity of the unguarded else block (or 1 if there is none).
          • The complexity of a switch statement is the number of cases, plus the complexity of each case block. It’s equivalent to the complexity of the equivalent cascade of if statements.
          • The complexity of a ternary expression (? :) is the complexity of the guard condition, plus the complexity of both expressions. It’s equivalent to the complexity of the equivalent if .. else construct.
          • The complexity of a try .. catch statement is the complexity of the try block, plus the complexity of each catch block.
          • The complexity of a return statement is the complexity of the expression (or 1 if there is none).
          • All other statements have a complexity of 1 and are discarded from the product.

        public static final Metric<ASTAnyTypeDeclaration,​Double> TIGHT_CLASS_COHESION
        The relative number of method pairs of a class that access in common at least one attribute of the measured class. TCC only counts direct attribute accesses, that is, only those attributes that are accessed in the body of the method.

        The value is a double between 0 and 1.

        TCC is taken to be a reliable cohesion metric for a class. High values (>70%) indicate a class with one basic function, which is hard to break into subcomponents. On the other hand, low values (<50%) may indicate that the class tries to do too much and defines several unrelated services, which is undesirable.


        public static final Metric<ASTAnyTypeDeclaration,​Integer> WEIGHED_METHOD_COUNT
        Sum of the statistical complexity of the operations in the class. We use CYCLO to quantify the complexity of an operation.

        WMC uses the same options as CYCLO, which are provided to CYCLO when computing it (JavaMetrics.CycloOption).


        public static final Metric<ASTAnyTypeDeclaration,​Double> WEIGHT_OF_CLASS
        Number of “functional” public methods divided by the total number of public methods. Our definition of “functional method” excludes constructors, getters, and setters.

        The value is a double between 0 and 1.

        This metric tries to quantify whether the measured class’ interface reveals more data than behaviour. Low values (less than 30%) indicate that the class reveals much more data than behaviour, which is a sign of poor encapsulation.