BooleanExpressionComplexity

Description

Since Checkstyle 3.4

Restrict the number of number of &&, ||, &, | and ^ in an expression.

Rationale: Too many conditions leads to code that is difficult to read and hence debug and maintain.

Note that the operators & and | are not only integer bitwise operators, they are also the non-shortcut versions of the boolean operators. && and ||.

Note that &, | and ^ are not checked if they are part of constructor or method call because they can be applied to non boolean variables and Checkstyle does not know types of methods from different classes.

Properties

name description type default value since
max the maximum allowed number of boolean operations in one expression. Integer 3 3.4
tokens tokens to check subset of tokens LAND, BAND, LOR, BOR, BXOR. LAND, BAND, LOR, BOR, BXOR. 3.4

Examples

To configure the check:

<module name="BooleanExpressionComplexity"/>
        

To configure the check with 7 allowed operation in boolean expression:

<module name="BooleanExpressionComplexity">
  <property name="max" value="7"/>
</module>
        

To configure the check to ignore & and |:

<module name="BooleanExpressionComplexity">
  <property name="tokens" value="BXOR,LAND,LOR"/>
</module>
        

Example of Usage

Error Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.metrics

Parent Module

TreeWalker

ClassDataAbstractionCoupling

Description

Since Checkstyle 3.4

This metric measures the number of instantiations of other classes within the given class. This type of coupling is not caused by inheritance or the object oriented paradigm. Generally speaking, any data type with other data types as members or local variable that is an instantiation (object) of another class has data abstraction coupling (DAC). The higher the DAC, the more complex the structure of the class.

This check processes files in the following way:

  1. Iterates over the list of tokens (defined below) and counts all mentioned classes.
  2. If a class was imported with direct import (i.e. import java.math.BigDecimal), or the class was referenced with the package name (i.e. java.math.BigDecimal value) and the package was added to the excludedPackages parameter, the class does not increase complexity.
  3. If a class name was added to the excludedClasses parameter, the class does not increase complexity.

Properties

name description type default value since
max the maximum threshold allowed Integer 7 3.4
excludedClasses User-configured class names to ignore String Set IllegalStateException, Set, StringBuilder, HashMap, ArrayList, String, float, SortedSet, long, RuntimeException, NullPointerException, TreeSet, List, Boolean, Void, Queue, Short, IllegalArgumentException, UnsupportedOperationException, HashSet, void, Character, IndexOutOfBoundsException, byte, double, SecurityException, TreeMap, Double, Deque, int, Exception, LinkedList, Integer, Float, StringBuffer, boolean, Byte, SortedMap, char, Long, short, Throwable, Object, Class, ArrayIndexOutOfBoundsException, Map 5.7
excludeClassesRegexps User-configured regular expressions to ignore classes Regular Expressions ^$ 7.7
excludedPackages User-configured packages to ignore String Set {} 7.7

Examples

To configure the check:

<module name="ClassDataAbstractionCoupling"/>
        

To configure the check with a threshold of 5:

<module name="ClassDataAbstractionCoupling">
  <property name="max" value="5"/>
</module>
        

To configure the check with two excluded classes HashMap and HashSet:

<module name="ClassDataAbstractionCoupling">
  <property name="excludedClasses" value="HashMap, HashSet"/>
</module>
        

To configure the check with two regular expressions ^Array.* and .*Exception$:

<module name="ClassDataAbstractionCoupling">
  <property name="excludeClassesRegexps"
    value="^Array.*, .*Exception$"/>
</module>
        

The following example demonstrates usage of excludedClasses and excludeClassesRegexps properties

Expected result is one class Date

<module name="ClassDataAbstractionCoupling">
  <property name="excludedClasses" value="ArrayList"/>
  <property name="excludeClassesRegexps" value="^Hash.*"/>
</module>
        
public class InputClassCoupling {
  public Set _set = new HashSet();
  public Map _map = new HashMap();
  public List<String> _list = new ArrayList<>();
  public Date _date = new Date();
}
        

To configure the check with two excluded classes HashMap and HashSet:

<module name="ClassDataAbstractionCoupling">
  <property name="excludedClasses" value="HashMap, HashSet"/>
</module>
        

To configure the check with two regular expressions ^Array.* and .*Exception$:

<module name="ClassDataAbstractionCoupling">
  <property name="excludeClassesRegexps" value="^Array.*, .*Exception$"/>
</module>
        

The following example demonstrates usage of excludedClasses and excludeClassesRegexps properties

Expected result is one class Date

<module name="ClassDataAbstractionCoupling">
  <property name="excludedClasses" value="ArrayList"/>
  <property name="excludeClassesRegexps" value="^Hash.*"/>
</module>
        
public class InputClassCoupling {
  public Set _set = new HashSet();
  public Map _map = new HashMap();
  public List<String> _list = new ArrayList<>();
  public Date _date = new Date();
}
        

Override property excludedPackages to mark some packages as excluded. Each member of excludedPackages should be a valid identifier:

  • java.util - valid, excludes all classes inside java.util, but not from the subpackages.
  • java.util. - invalid, should not end with a dot.
  • java.util.* - invalid, should not end with a star.

Note, that checkstyle will ignore all classes from the java.lang package and its subpackages, even if the java.lang was not listed in the excludedPackages parameter.

Also node, that excludedPackages will not exclude classes, imported via wildcard (e.g. import java.math.*). Instead of wildcard import you should use direct import (e.g. import java.math.BigDecimal).

Also note, that checkstyle will not exclude classes within the same file even if it was listed in the excludedPackages parameter. For example, assuming the config is

<module name="ClassDataAbstractionCoupling">
  <property name="excludedPackages" value="a.b"/>
</module>
          
And the file a.b.Foo.java is:
package a.b;

import a.b.Bar;
import a.b.c.Baz;

public class Foo {
  public Bar bar; // Will be ignored, located inside ignored a.b package
  public Baz baz; // Will not be ignored, located inside a.b.c package
  public Data data; // Will not be ignored, same file

  class Data {
    public Foo foo; // Will not be ignored, same file
  }
}
          
The bar member will not be counted, since the a.b added to the excludedPackages. The baz member will be counted, since the a.b.c was not added to the excludedPackages. The data and foo members will be counted, as they are inside same file.

Example of usage:

<module name="ClassDataAbstractionCoupling">
  <property name="excludedPackages" value="java.util, java.math"/>
</module>
        

Example of Usage

Error Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.metrics

Parent Module

TreeWalker

ClassFanOutComplexity

Description

Since Checkstyle 3.4

The number of other classes a given class relies on. Also the square of this has been shown to indicate the amount of maintenance required in functional programs (on a file basis) at least.

This check processes files in the following way:

  1. Iterates over the list of tokens (defined below) and counts all mentioned classes.
  2. If a class was imported with direct import (i.e. import java.math.BigDecimal), or the class was referenced with the package name (i.e. java.math.BigDecimal value) and the package was added to the excludedPackages parameter, the class does not increase complexity.
  3. If a class name was added to the excludedClasses parameter, the class does not increase complexity.

Properties

name description type default value since
max the maximum threshold allowed Integer 20 3.4
excludedClasses User-configured class names to ignore String Set IllegalStateException, Set, StringBuilder, HashMap, ArrayList, String, float, SortedSet, long, RuntimeException, NullPointerException, TreeSet, List, Boolean, Void, Queue, Short, IllegalArgumentException, UnsupportedOperationException, HashSet, void, Character, IndexOutOfBoundsException, byte, double, SecurityException, TreeMap, Double, Deque, int, Exception, LinkedList, Integer, Float, StringBuffer, boolean, Byte, SortedMap, char, Long, short, Throwable, Object, Class, ArrayIndexOutOfBoundsException, Map 5.7
excludeClassesRegexps User-configured regular expressions to ignore classes Regular Expressions ^$ 7.7
excludedPackages User-configured packages to ignore String Set {} 7.7

Examples

To configure the check:

<module name="ClassFanOutComplexity"/>
        

To configure the check with a threshold of 10:

<module name="ClassFanOutComplexity">
  <property name="max" value="10"/>
</module>
        

Override property excludedPackages to mark some packages as excluded. Each member of excludedPackages should be a valid identifier:

  • java.util - valid, excludes all classes inside java.util, but not from the subpackages.
  • java.util. - invalid, should not end with a dot.
  • java.util.* - invalid, should not end with a star.

Note, that checkstyle will ignore all classes from the java.lang package and its subpackages, even if the java.lang was not listed in the excludedPackages parameter.

Also node, that excludedPackages will not exclude classes, imported via wildcard (e.g. import java.math.*). Instead of wildcard import you should use direct import (e.g. import java.math.BigDecimal).

Also note, that checkstyle will not exclude classes within the same file even if it was listed in the excludedPackages parameter. For example, assuming the config is

<module name="ClassDataAbstractionCoupling">
  <property name="excludedPackages" value="a.b"/>
</module>
          
And the file a.b.Foo.java is:
package a.b;

import a.b.Bar;
import a.b.c.Baz;

public class Foo {
  public Bar bar; // Will be ignored, located inside ignored a.b package
  public Baz baz; // Will not be ignored, located inside a.b.c package
  public Data data; // Will not be ignored, same file

  class Data {
    public Foo foo; // Will not be ignored, same file
  }
}
          
The bar member will not be counted, since the a.b added to the excludedPackages. The baz member will be counted, since the a.b.c was not added to the excludedPackages. The data and foo members will be counted, as they are inside same file.

Example of usage:

<module name="ClassFanOutComplexity">
  <property name="excludedPackages" value="java.util, java.math"/>
</module>
        

Example of Usage

Error Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.metrics

Parent Module

TreeWalker

CyclomaticComplexity

Description

Since Checkstyle 3.2

Checks cyclomatic complexity against a specified limit. It is a measure of the minimum number of possible paths through the source and therefore the number of required tests, it is not a about quality of code! It is only applied to methods, c-tors, static initializers and instance initializers.
The complexity is equal to the number of decision points + 1 Decision points: if, while , do, for, ?:, catch , switch, case statements, and operators && and || in the body of target.
By pure theory level 1-4 is considered easy to test, 5-7 OK, 8-10 consider re-factoring to ease testing, and 11+ re-factor now as testing will be painful.
When it comes to code quality measurement by this metric level 10 is very good level as a ultimate target (that is hard to archive). Do not be ashamed to have complexity level 15 or even higher, but keep it below 20 to catch really bad designed code automatically.
Please use Suppression to avoid violations on cases that could not be split in few methods without damaging readability of code or encapsulation.

Properties

name description type default value since
max the maximum threshold allowed Integer 10 3.2
switchBlockAsSingleDecisionPoint whether to treat the whole switch block as a single decision point Boolean false 6.11
tokens tokens to check subset of tokens LITERAL_WHILE, LITERAL_DO, LITERAL_FOR, LITERAL_IF, LITERAL_SWITCH, LITERAL_CASE, LITERAL_CATCH, QUESTION, LAND, LOR. LITERAL_WHILE, LITERAL_DO, LITERAL_FOR, LITERAL_IF, LITERAL_SWITCH, LITERAL_CASE, LITERAL_CATCH, QUESTION, LAND, LOR. 3.2

Examples

To configure the check:

<module name="CyclomaticComplexity"/>
        

To configure the check with a threshold of 15:

<module name="CyclomaticComplexity">
  <property name="max" value="15"/>
</module>
        

Explanation on how complexity is calculated (switchBlockAsSingleDecisionPoint is set to false):

class CC {
  // Cyclomatic Complexity = 12
  public void doSmth()  {         // 1
    if (a == b)  {                // 2
      if (a1 == b1                // 3
        && c1 == d1) {            // 4
        fiddle();
      }
      else if (a2 == b2           // 5
              || c1 < d1) {       // 6
        fiddle();
      }
      else {
        fiddle();
      }
    }
    else if (c == d) {            // 7
      while (c == d) {            // 8
        fiddle();
      }
    }
    else if (e == f) {
      for (n = 0; n < h            // 9
            || n < 6; n++) {       // 10
        fiddle();
      }
    }
      else {
        switch (z) {
          case 1:                  // 11
            fiddle();
            break;
          case 2:                  // 12
            fiddle();
            break;
          default:
            fiddle();
            break;
      }
    }
  }
}        

Explanation on how complexity is calculated (switchBlockAsSingleDecisionPoint is set to true):

class SwitchExample {
  // Cyclomatic Complexity = 2
  public void doSmth()  {          // 1
    int z = 1;
    switch (z) {                   // 2
      case 1:
        foo1();
        break;
      case 2:
        foo2();
        break;
      default:
        fooDefault();
        break;
     }
  }
}        

Example of Usage

Error Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.metrics

Parent Module

TreeWalker

JavaNCSS

Description

Since Checkstyle 3.5

Determines complexity of methods, classes and files by counting the Non Commenting Source Statements (NCSS). This check adheres to the specification for the JavaNCSS-Tool written by Chr. Clemens Lee.
Roughly said the NCSS metric is calculated by counting the source lines which are not comments, (nearly) equivalent to counting the semicolons and opening curly braces.
The NCSS for a class is summarized from the NCSS of all its methods, the NCSS of its nested classes and the number of member variable declarations.
The NCSS for a file is summarized from the ncss of all its top level classes, the number of imports and the package declaration.

Rationale: Too large methods and classes are hard to read and costly to maintain. A large NCSS number often means that a method or class has too many responsibilities and/or functionalities which should be decomposed into smaller units.

Properties

name description type default value since
methodMaximum the maximum allowed number of non commenting lines in a method. Integer 50 3.5
classMaximum the maximum allowed number of non commenting lines in a class. Integer 1500 3.5
fileMaximum the maximum allowed number of non commenting lines in a file including all top level and nested classes. Integer 2000 3.5

Examples

To configure the check:

<module name="JavaNCSS"/>
        

To configure the check with 40 allowed non commenting lines for a method:

<module name="JavaNCSS">
  <property name="methodMaximum" value="40"/>
</module>
        

Example of Usage

Error Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.metrics

Parent Module

TreeWalker

NPathComplexity

Description

Since Checkstyle 3.4

The NPATH metric computes the number of possible execution paths through a function(method). It takes into account the nesting of conditional statements and multi-part boolean expressions (A && B, C || D, E ? F :G and their combinations).
The NPATH metric was designed base on Cyclomatic complexity to avoid problem of Cyclomatic complexity metric like nesting level within a function(method).

Metric was described at "NPATH: a measure of execution pathcomplexity and its applications". If you need detailed description of algorithm, please read that article, it is well written and have number of examples and details.

Here is some quotes:

An NPATH threshold value of 200 has been established for a function. The value 200 is based on studies done at AT&T Bell Laboratories [1988 year].
Some of the most effective methods of reducing the NPATH value include
- distributing functionality,
- implementing multiple if statements as a switch statement
- creating a separate function for logical expressions with a high count of and (&&) and or (||) operators.
Although strategies to reduce the NPATH complexity of functions are important, care must be taken not to distort the logical clarity of the software by applying a strategy to reduce the complexity of functions. That is, there is a point of diminishing return beyond which a further attempt at reduction of complexity distorts the logical clarity of the system structure.
Structure Complexity expression
if ([expr]) { [if-range] } NP(if-range) + 1 + NP(expr)
if ([expr]) { [if-range] } else { [else-range] } NP(if-range) + NP(else-range) + NP(expr)
while ([expr]) { [while-range] } NP(while-range) + NP(expr) + 1
do { [do-range] } while ([expr]) NP(do-range) + NP(expr) + 1
for([expr1]; [expr2]; [expr3]) { [for-range] } NP(for-range) + NP(expr1) + NP(expr2) + NP(expr3) + 1
switch ([expr]) { case : [case-range] default: [default-range] } S(i=1:i=n)NP(case-range[i]) + NP(default-range) + NP(expr)
[expr1] ? [expr2] : [expr3] NP(expr1) + NP(expr2) + NP(expr3) + 2
goto label 1
break 1
Expressions Number of && and || operators in expression. No operators - 0
continue 1
return 1
Statement (even sequential statements) 1
Empty block {} 1
Function call 1
Function(Method) declaration or Block P(i=1:i=N)NP(Statement[i])

Rationale: Nejmeh says that his group had an informal NPATH limit of 200 on individual routines; functions(methods) that exceeded this value were candidates for further decomposition - or at least a closer look. Please do not be fanatic with limit 200 - choose number that suites your project style. Limit 200 is empirical number base on some sources of at AT&T Bell Laboratories of 1988 year.

Properties

name description type default value since
max the maximum threshold allowed Integer 200 3.4

Examples

To configure the check:

<module name="NPathComplexity"/>
        

To configure the check with a threshold of 1000:

<module name="NPathComplexity">
  <property name="max" value="1000"/>
</module>
        

Example of Usage

Error Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.metrics

Parent Module

TreeWalker