BooleanExpressionComplexity

Description

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
max the maximum allowed number of boolean operations in one expression. integer 3
tokens tokens to check subset of tokens LAND, BAND, LOR, BOR, BXOR. LAND, BAND, LOR, BOR, BXOR.

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 suite you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.metrics

Parent Module

TreeWalker

ClassDataAbstractionCoupling

Description

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.

Properties

name description type default value
max the maximum threshold allowed integer 7
excludedClasses User-configured class names to ignore String Set boolean, byte, char, double, float, int, long, short, void, Boolean, Byte, Character, Double, Float, Integer, Long, Short, Void, Object, Class, String, StringBuffer, StringBuilder, ArrayIndexOutOfBoundsException, Exception, RuntimeException, IllegalArgumentException, IllegalStateException, IndexOutOfBoundsException, NullPointerException, Throwable, SecurityException, UnsupportedOperationException, List, ArrayList, Deque, Queue, LinkedList, Set, HashSet, SortedSet, TreeSet, Map, HashMap, SortedMap, TreeMap

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>
        

Example of Usage

Error Messages

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

Package

com.puppycrawl.tools.checkstyle.checks.metrics

Parent Module

TreeWalker

ClassFanOutComplexity

Description

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.

Properties

name description type default value
max the maximum threshold allowed integer 20
excludedClasses User-configured class names to ignore String Set boolean, byte, char, double, float, int, long, short, void, Boolean, Byte, Character, Double, Float, Integer, Long, Short, Void, Object, Class, String, StringBuffer, StringBuilder, ArrayIndexOutOfBoundsException, Exception, RuntimeException, IllegalArgumentException, IllegalStateException, IndexOutOfBoundsException, NullPointerException, Throwable, SecurityException, UnsupportedOperationException, List, ArrayList, Deque, Queue, LinkedList, Set, HashSet, SortedSet, TreeSet, Map, HashMap, SortedMap, TreeMap

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>
        

Example of Usage

Error Messages

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

Package

com.puppycrawl.tools.checkstyle.checks.metrics

Parent Module

TreeWalker

CyclomaticComplexity

Description

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
max the maximum threshold allowed integer 10
switchBlockAsSingleDecisionPoint whether to treat the whole switch block as a single decision point boolean false
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.

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 suite you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.metrics

Parent Module

TreeWalker

JavaNCSS

Description

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
methodMaximum the maximum allowed number of non commenting lines in a method. integer 50
classMaximum the maximum allowed number of non commenting lines in a class. integer 1500
fileMaximum the maximum allowed number of non commenting lines in a file including all top level and nested classes. integer 2000

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 suite you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.metrics

Parent Module

TreeWalker

NPathComplexity

Description

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

Metric was described at "NPATH: a measure of execution pathcomplexity and its applications". If you need detaled 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) + NP(expr) + 1
if [expr] { [if-range] } esle { [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] } NP(expr) + S(i=1:i=n)NP(case-range(i)) + NP(default-range)
[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 1 (even sequential statements)
Function call 1
C function 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 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
max the maximum threshold allowed integer 200
tokens tokens to check subset of tokens LITERAL_WHILE, LITERAL_DO, LITERAL_FOR, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH, LITERAL_CASE, LITERAL_TRY, LITERAL_CATCH, QUESTION. LITERAL_WHILE, LITERAL_DO, LITERAL_FOR, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH, LITERAL_CASE, LITERAL_TRY, LITERAL_CATCH, QUESTION.

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 suite you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.metrics

Parent Module

TreeWalker