Since Checkstyle 3.4
Restricts the number of boolean operators (&&
, ||
,
&
, |
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.
To configure the check:
<module name="BooleanExpressionComplexity"/>
Code Example:
public class Test { public static void main(String ... args) { boolean a = true; boolean b = false; boolean c = (a & b) | (b ^ a); // OK, 1(&) + 1(|) + 1(^) = 3 (max allowed 3) boolean d = (a & b) ^ (a || b) | a; // violation, 1(&) + 1(^) + 1(||) + 1(|) = 4 } }
To configure the check with 5 allowed operation in boolean expression:
<module name="BooleanExpressionComplexity"> <property name="max" value="5"/> </module>
Code Example:
public class Test { public static void main(String ... args) { boolean a = true; boolean b = false; boolean c = (a & b) | (b ^ a) | (a ^ b); // OK, 1(&) + 1(|) + 1(^) + 1(|) + 1(^) = 5 boolean d = (a | b) ^ (a | b) ^ (a || b) & b; // violation, // 1(|) + 1(^) + 1(|) + 1(^) + 1(||) + 1(&) = 6 } }
To configure the check to ignore &
and
|
:
<module name="BooleanExpressionComplexity"> <property name="tokens" value="BXOR,LAND,LOR"/> </module>
Code Example:
public class Test { public static void main(String ... args) { boolean a = true; boolean b = false; boolean c = (!a && b) | (a || !b) ^ a; // OK, 1(&&) + 1(||) + 1(^) = 3 // | is ignored here boolean d = a ^ (a || b) ^ (b || a) & a; // violation, 1(^) + 1(||) + 1(^) + 1(||) = 4 // & is ignored here } }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.metrics
Since Checkstyle 3.4
Measures the number of instantiations of other classes within the given class or record. 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:
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.
excludedClasses
parameter,
the class does not increase complexity.
name | description | type | default value | since |
---|---|---|---|---|
max | Specify the maximum threshold allowed. | int | 7 |
3.4 |
excludedClasses | Specify user-configured class names to ignore. | String[] |
ArrayIndexOutOfBoundsException, ArrayList, Boolean, Byte,
Character, Class, Collection, Deprecated, Deque, Double, DoubleStream, EnumSet,
Exception, Float, FunctionalInterface, HashMap, HashSet, IllegalArgumentException,
IllegalStateException, IndexOutOfBoundsException, IntStream, Integer,
LinkedHashMap, LinkedHashSet, LinkedList, List, Long, LongStream, Map,
NullPointerException, Object, Optional, OptionalDouble, OptionalInt, OptionalLong,
Override, Queue, RuntimeException, SafeVarargs, SecurityException, Set, Short,
SortedMap, SortedSet, Stream, String, StringBuffer, StringBuilder,
SuppressWarnings, Throwable, TreeMap, TreeSet, UnsupportedOperationException, Void,
boolean, byte, char, double, float, int, long, short, var, void
|
5.7 |
excludeClassesRegexps | Specify user-configured regular expressions to ignore classes. | Regular Expressions | ^$ |
7.7 |
excludedPackages | Specify user-configured packages to ignore. | String[] | {} |
7.7 |
To configure the check:
<module name="ClassDataAbstractionCoupling"/>
Example:
The check passes without violations in the following:
class InputClassCoupling { Set set = new HashSet(); // HashSet ignored due to default excludedClasses property Map map = new HashMap(); // HashMap ignored due to default excludedClasses property Date date = new Date(); // Counted, 1 Time time = new Time(); // Counted, 2 Place place = new Place(); // Counted, 3 }
The check results in a violation in the following:
class InputClassCoupling { Set set = new HashSet(); // HashSet ignored due to default excludedClasses property Map map = new HashMap(); // HashMap ignored due to default excludedClasses property Date date = new Date(); // Counted, 1 Time time = new Time(); // Counted, 2 // instantiation of 5 other user defined classes Place place = new Place(); // violation, total is 8 }
To configure the check with a threshold of 2:
<module name="ClassDataAbstractionCoupling"> <property name="max" value="2"/> </module>
Example:
The check passes without violations in the following:
class InputClassCoupling { Set set = new HashSet(); // HashSet ignored due to default excludedClasses property Map map = new HashMap(); // HashMap ignored due to default excludedClasses property Date date = new Date(); // Counted, 1 Time time = new Time(); // Counted, 2 }
The check results in a violation in the following:
class InputClassCoupling { Set set = new HashSet(); // HashSet ignored due to default excludedClasses property Map map = new HashMap(); // HashMap ignored due to default excludedClasses property Date date = new Date(); // Counted, 1 Time time = new Time(); // Counted, 2 Place place = new Place(); // violation, total is 3 }
To configure the check with three excluded classes HashMap
,
HashSet
and Place
:
<module name="ClassDataAbstractionCoupling"> <property name="excludedClasses" value="HashMap, HashSet, Place"/> </module>
Example:
The check passes without violations in the following:
class InputClassCoupling { Set set = new HashSet(); // Ignored Map map = new HashMap(); // Ignored Date date = new Date(); // Counted, 1 Time time = new Time(); // Counted, 2 // instantiation of 5 other user defined classes Place place = new Place(); // Ignored }
The check results in a violation in the following:
class InputClassCoupling { Set set = new HashSet(); // Ignored Map map = new HashMap(); // Ignored Date date = new Date(); // Counted, 1 Time time = new Time(); // Counted, 2 // instantiation of 5 other user defined classes Space space = new Space(); // violation, total is 8 }
To configure the check to exclude classes with a regular expression
.*Reader$
:
<module name="ClassDataAbstractionCoupling"> <property name="excludeClassesRegexps" value=".*Reader$"/> </module>
Example:
The check passes without violations in the following:
class InputClassCoupling { Set set = new HashSet(); // HashSet ignored due to default excludedClasses property Map map = new HashMap(); // HashMap ignored due to default excludedClasses property Date date = new Date(); // Counted, 1 Time time = new Time(); // Counted, 2 // instantiation of 5 other user defined classes BufferedReader br = new BufferedReader(); // Ignored }
The check results in a violation in the following:
class InputClassCoupling { Set set = new HashSet(); // HashSet ignored due to default excludedClasses property Map map = new HashMap(); // HashMap ignored due to default excludedClasses property Date date = new Date(); // Counted, 1 Time time = new Time(); // Counted, 2 // instantiation of 5 other user defined classes File file = new File(); // violation, total is 8 }
To configure the check with an excluded package java.io
:
<module name="ClassDataAbstractionCoupling"> <property name="excludedPackages" value="java.io"/> </module>
Example:
The check passes without violations in the following:
import java.io.BufferedReader; class InputClassCoupling { Set set = new HashSet(); // HashSet ignored due to default excludedClasses property Map map = new HashMap(); // HashMap ignored due to default excludedClasses property Date date = new Date(); // Counted, 1 Time time = new Time(); // Counted, 2 // instantiation of 5 other user defined classes BufferedReader br = new BufferedReader(); // Ignored }
The check results in a violation in the following:
import java.util.StringTokenizer; class InputClassCoupling { Set set = new HashSet(); // HashSet ignored due to default excludedClasses property Map map = new HashMap(); // HashMap ignored due to default excludedClasses property Date date = new Date(); // Counted, 1 Time time = new Time(); // Counted, 2 // instantiation of 5 other user defined classes StringTokenizer st = new StringTokenizer(); // violation, total is 8 }
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 note, 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; class Foo { Bar bar; // Will be ignored, located inside ignored a.b package Baz baz; // Will not be ignored, located inside a.b.c package Data data; // Will not be ignored, same file class Data { 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.
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.metrics
Since Checkstyle 3.4
Checks the number of other types a given class/record/interface/enum/annotation 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:
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.
excludedClasses
parameter,
the class does not increase complexity.
name | description | type | default value | since |
---|---|---|---|---|
max | Specify the maximum threshold allowed. | int | 20 |
3.4 |
excludedClasses | Specify user-configured class names to ignore. | String[] |
ArrayIndexOutOfBoundsException, ArrayList, Boolean, Byte,
Character, Class, Collection, Deprecated, Deque, Double, DoubleStream, EnumSet,
Exception, Float, FunctionalInterface, HashMap, HashSet, IllegalArgumentException,
IllegalStateException, IndexOutOfBoundsException, IntStream, Integer,
LinkedHashMap, LinkedHashSet, LinkedList, List, Long, LongStream, Map,
NullPointerException, Object, Optional, OptionalDouble, OptionalInt, OptionalLong,
Override, Queue, RuntimeException, SafeVarargs, SecurityException, Set, Short,
SortedMap, SortedSet, Stream, String, StringBuffer, StringBuilder,
SuppressWarnings, Throwable, TreeMap, TreeSet, UnsupportedOperationException, Void,
boolean, byte, char, double, float, int, long, short, var, void
|
5.7 |
excludeClassesRegexps | Specify user-configured regular expressions to ignore classes. | Regular Expressions | ^$ |
7.7 |
excludedPackages | Specify user-configured packages to ignore. All excluded packages should end with a period, so it also appends a dot to a package name. | String[] | {} |
7.7 |
To configure the check:
<module name="ClassFanOutComplexity"/>
Example:
The check passes without violations in the following:
class InputClassComplexity { Set set = new HashSet(); // Set, HashSet ignored due to default excludedClasses property Map map = new HashMap(); // Map, HashMap ignored due to default excludedClasses property Date date = new Date(); // Counted, 1 Time time = new Time(); // Counted, 2 Place place = new Place(); // Counted, 3 int value = 10; // int is ignored due to default excludedClasses property void method() { var result = "result"; // var is ignored due to default excludedClasses property } }
The check results in a violation in the following:
class InputClassComplexity { Set set = new HashSet(); // Set, HashSet ignored due to default excludedClasses property Map map = new HashMap(); // Map, HashMap ignored due to default excludedClasses property Date date = new Date(); // Counted, 1 Time time = new Time(); // Counted, 2 // mention of 18 other user defined classes Place place = new Place(); // violation, total is 21 }
To configure the check with a threshold of 2:
<module name="ClassFanOutComplexity"> <property name="max" value="2"/> </module>
Example:
The check passes without violations in the following:
class InputClassComplexity { Set set = new HashSet(); // Set, HashSet ignored due to default excludedClasses property Map map = new HashMap(); // Map, HashMap ignored due to default excludedClasses property Date date = new Date(); // Counted, 1 Time time = new Time(); // Counted, 2 }
The check results in a violation in the following:
class InputClassComplexity { Set set = new HashSet(); // Set, HashSet ignored due to default excludedClasses property Map map = new HashMap(); // Map, HashMap ignored due to default excludedClasses property Date date = new Date(); // Counted, 1 Time time = new Time(); // Counted, 2 Place place = new Place(); // violation, total is 3 }
To configure the check with three excluded classes HashMap
,
HashSet
and Place
:
<module name="ClassFanOutComplexity"> <property name="excludedClasses" value="HashMap, HashSet, Place"/> </module>
Example:
The check passes without violations in the following:
class InputClassComplexity { Set set = new HashSet(); // Set counted 1, HashSet ignored Map map = new HashMap(); // Map counted 2, HashMap ignored Date date = new Date(); // Counted, 3 Time time = new Time(); // Counted, 4 // mention of 16 other user defined classes Place place = new Place(); // Ignored }
The check results in a violation in the following:
class InputClassComplexity { Set set = new HashSet(); // Set counted 1, HashSet ignored Map map = new HashMap(); // Map counted 2, HashMap ignored Date date = new Date(); // Counted, 3 Time time = new Time(); // Counted, 4 // mention of 16 other user defined classes Space space = new Space(); // violation, total is 21 }
To configure the check to exclude classes with a regular expression
.*Reader$
:
<module name="ClassFanOutComplexity"> <property name="excludeClassesRegexps" value=".*Reader$"/> </module>
Example:
The check passes without violations in the following:
class InputClassComplexity { Set set = new HashSet(); // Set, HashSet ignored due to default excludedClasses property Map map = new HashMap(); // Map, HashMap ignored due to default excludedClasses property Date date = new Date(); // Counted, 1 Time time = new Time(); // Counted, 2 // mention of 18 other user defined classes BufferedReader br; // Ignored }
The check results in a violation in the following:
class InputClassComplexity { Set set = new HashSet(); // Set, HashSet ignored due to default excludedClasses property Map map = new HashMap(); // Map, HashMap ignored due to default excludedClasses property Date date = new Date(); // Counted, 1 Time time = new Time(); // Counted, 2 // mention of 18 other user defined classes File file; // violation, total is 21 }
To configure the check with an excluded package java.io
:
<module name="ClassFanOutComplexity"> <property name="excludedPackages" value="java.io"/> </module>
Example:
The check passes without violations in the following:
import java.io.BufferedReader; class InputClassComplexity { Set set = new HashSet(); // Set, HashSet ignored due to default excludedClasses property Map map = new HashMap(); // Map, HashMap ignored due to default excludedClasses property Date date = new Date(); // Counted, 1 Time time = new Time(); // Counted, 2 // mention of 18 other user defined classes BufferedReader br; // Ignored }
The check results in a violation in the following:
import java.util.StringTokenizer; class InputClassComplexity { Set set = new HashSet(); // Set, HashSet ignored due to default excludedClasses property Map map = new HashMap(); // Map, HashMap ignored due to default excludedClasses property Date date = new Date(); // Counted, 1 Time time = new Time(); // Counted, 2 // mention of 18 other user defined classes StringTokenizer st; // violation, total is 21 }
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 note, 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="ClassFanOutComplexity"> <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; class Foo { Bar bar; // Will be ignored, located inside ignored a.b package Baz baz; // Will not be ignored, located inside a.b.c package Data data; // Will not be ignored, same file class Data { 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.
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.metrics
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.
name | description | type | default value | since |
---|---|---|---|---|
max | Specify the maximum threshold allowed. | int | 10 |
3.2 |
switchBlockAsSingleDecisionPoint | Control 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 |
To configure the check:
<module name="CyclomaticComplexity"/>
Example:
class CyclomaticComplexity { // Cyclomatic Complexity = 11 int a, b, c, d, n; public void foo() { // 1, function declaration if (a == 1) { // 2, if fun1(); } else if (a == b // 3, if && a == c) { // 4, && operator if (c == 2) { // 5, if fun2(); } } else if (a == d) { // 6, if try { fun4(); } catch (Exception e) { // 7, catch } } else { switch(n) { case 1: // 8, case fun1(); break; case 2: // 9, case fun2(); break; case 3: // 10, case fun3(); break; default: break; } } d = a < 0 ? -1 : 1; // 11, ternary operator } }
To configure the check with a threshold of 4 and check only for while and do-while loops:
<module name="CyclomaticComplexity"> <property name="max" value="4"/> <property name="tokens" value="LITERAL_WHILE, LITERAL_DO"/> </module>
Example:
class CyclomaticComplexity { // Cyclomatic Complexity = 5 int a, b, c, d; public void foo() { // 1, function declaration while (a < b // 2, while && a > c) { fun(); } if (a == b) { do { // 3, do fun(); } while (d); } else if (c == d) { while (c > 0) { // 4, while fun(); } do { // 5, do-while fun(); } while (a); } } }
To configure the check to consider switch-case block as one decision point.
<module name="CyclomaticComplexity"> <property name="switchBlockAsSingleDecisionPoint" value="true"/> </module>
Example:
class CyclomaticComplexity { // Cyclomatic Complexity = 11 int a, b, c, d, e, n; public void foo() { // 1, function declaration if (a == b) { // 2, if fun1(); } else if (a == 0 // 3, if && b == c) { // 4, && operator if (c == -1) { // 5, if fun2(); } } else if (a == c // 6, if || a == d) { // 7, || operator fun3(); } else if (d == e) { // 8, if try { fun4(); } catch (Exception e) { // 9, catch } } else { switch(n) { // 10, switch case 1: fun1(); break; case 2: fun2(); break; default: break; } } a = a > 0 ? b : c; // 11, ternary operator } }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.metrics
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.
name | description | type | default value | since |
---|---|---|---|---|
methodMaximum | Specify the maximum allowed number of non commenting lines in a method. | int | 50 |
3.5 |
classMaximum | Specify the maximum allowed number of non commenting lines in a class. | int | 1500 |
3.5 |
fileMaximum | Specify the maximum allowed number of non commenting lines in a file including all top level and nested classes. | int | 2000 |
3.5 |
recordMaximum | Specify the maximum allowed number of non commenting lines in a record. | int | 150 |
8.36 |
To configure the check:
<module name="JavaNCSS"/>
Example:
public void test() { System.out.println("Line 1"); // another 48 lines of code System.out.println("Line 50") // OK System.out.println("Line 51") // violation, the method crosses 50 non commented lines }
To configure the check with 40 allowed non commented lines for a method:
<module name="JavaNCSS"> <property name="methodMaximum" value="40"/> </module>
Example:
public void test() { System.out.println("Line 1"); // another 38 lines of code System.out.println("Line 40") // OK System.out.println("Line 41") // violation, the method crosses 40 non commented lines }
To configure the check to set limit of non commented lines in class to 100:
<module name="JavaNCSS"> <property name="classMaximum" value="100"/> </module>
Example:
public class Test { public void test() { System.out.println("Line 1"); // another 47 lines of code System.out.println("Line 49"); } public void test1() { System.out.println("Line 50"); // OK // another 47 lines of code System.out.println("Line 98"); // violation } }
To configure the check to set limit of non commented lines in file to 200:
<module name="JavaNCSS"> <property name="fileMaximum" value="200"/> </module>
Example:
public class Test1 { public void test() { System.out.println("Line 1"); // another 48 lines of code System.out.println("Line 49"); } public void test1() { System.out.println("Line 50"); // another 47 lines of code System.out.println("Line 98"); // OK } } class Test2 { public void test() { System.out.println("Line 150"); // OK } public void test1() { System.out.println("Line 200"); // violation } }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.metrics
Since Checkstyle 3.4
Checks the NPATH complexity against a specified limit.
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 variables 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.
name | description | type | default value | since |
---|---|---|---|---|
max | Specify the maximum threshold allowed. | int | 200 |
3.4 |
To configure the check:
<module name="NPathComplexity"/>
Example:
public abstract class Test { final int a = 0; int b = 0; public void foo() { // OK, NPath complexity is less than default threshold // function consists of one if-else block with an NPath Complexity of 3 if (a > 10) { if (a > b) { // nested if-else decision tree adds 2 to the complexity count buzz(); } else { fizz(); } } else { // last possible outcome of the main if-else block, adds 1 to complexity buzz(); } } public void boo() { // violation, NPath complexity is 217 (max allowed is 200) // looping through 3 switch statements produces 6^3 + 1 (217) possible outcomes for(int i = 0; i < b; i++) { // for statement adds 1 to final complexity switch(i) { // each independent switch statement multiplies complexity by 6 case a: // ternary with && adds 3 to switch's complexity print(f(i) && g(i) ? fizz() : buzz()); default: // ternary with || adds 3 to switch's complexity print(f(i) || g(i) ? fizz() : buzz()); } switch(i - 1) { // multiplies complexity by 6 case a: print(f(i) && g(i) ? fizz() : buzz()); default: print(f(i) || g(i) ? fizz() : buzz()); } switch(i + 1) { // multiplies complexity by 6 case a: print(f(i) && g(i) ? fizz() : buzz()); default: print(f(i) || g(i) ? fizz() : buzz()); } } } public abstract boolean f(int x); public abstract boolean g(int x); public abstract String fizz(); public abstract String buzz(); public abstract void print(String str); }
To configure the check with a threshold of 100:
<module name="NPathComplexity"> <property name="max" value="100"/> </module>
Example:
public abstract class Test1 { public void foo() { // violation, NPath complexity is 128 (max allowed is 100) int a,b,t,m,n; a=b=t=m=n = 0; // Complexity is achieved by choosing from 2 options 7 times (2^7 = 128 possible outcomes) if (a > b) { // non-nested if-else decision tree multiplies complexity by 2 bar(); } else { baz(); } print(t > 1 ? bar() : baz()); // 5 ternary statements multiply complexity by 2^5 print(t > 2 ? bar() : baz()); print(t > 3 ? bar() : baz()); print(t > 4 ? bar() : baz()); print(t > 5 ? bar() : baz()); if (m > n) { // multiplies complexity by 2 baz(); } else { bar(); } } public abstract String bar(); public abstract String baz(); public abstract void print(String str); }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.metrics