public final class NPathComplexityCheck extends AbstractCheck
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.
max - Specify the maximum threshold allowed.
Type is int.
Default value is 200.
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);
}
Parent is com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
npathComplexity
| Modifier and Type | Class and Description |
|---|---|
private static class |
NPathComplexityCheck.TokenEnd
Coordinates of token end.
|
private static class |
NPathComplexityCheck.Values
Class that store range value and expression value.
|
AutomaticBean.OutputStreamOptions| Modifier and Type | Field and Description |
|---|---|
private java.util.Deque<java.lang.Boolean> |
afterValues
Stack of belongs to range values for question operator.
|
private boolean |
branchVisited
True, when branch is visited, but not leaved.
|
private java.math.BigInteger |
currentRangeValue
NP value for current range.
|
private static int |
DEFAULT_MAX
Default allowed complexity.
|
private java.util.Deque<java.lang.Integer> |
expressionValues
Stack of NP values for expressions.
|
private static java.math.BigInteger |
INITIAL_VALUE
The initial current value.
|
private int |
max
Specify the maximum threshold allowed.
|
static java.lang.String |
MSG_KEY
A key is pointing to the warning message text in "messages.properties"
file.
|
private NPathComplexityCheck.TokenEnd |
processingTokenEnd
Range of the last processed expression.
|
private java.util.Deque<java.math.BigInteger> |
rangeValues
Stack of NP values for ranges.
|
| Constructor and Description |
|---|
NPathComplexityCheck() |
| Modifier and Type | Method and Description |
|---|---|
void |
beginTree(DetailAST rootAST)
Called before the starting to process a tree.
|
private static int |
countCaseConstants(DetailAST ast)
Counts number of case constants (EXPR) tokens in a switch labeled rule.
|
private static int |
countCaseTokens(DetailAST ast)
Counts number of case tokens subject to a case group token.
|
private static int |
countConditionalOperators(DetailAST ast)
Calculates number of conditional operators, including inline ternary operator, for a token.
|
int[] |
getAcceptableTokens()
The configurable token set.
|
int[] |
getDefaultTokens()
Returns the default token a check is interested in.
|
private static DetailAST |
getLastToken(DetailAST ast)
Finds a leaf, which is the most distant from the root.
|
int[] |
getRequiredTokens()
The tokens that this check must be registered for.
|
private void |
leaveAddingConditional()
Leaves catch.
|
private void |
leaveBranch()
Leaves else, default or case group tokens.
|
private void |
leaveConditional()
Leaves while, do, for, if, ternary (?::), return or switch.
|
private void |
leaveMethodDef(DetailAST ast)
Process the end of a method definition.
|
private void |
leaveMultiplyingConditional()
Leaves try.
|
void |
leaveToken(DetailAST ast)
Called after all the child nodes have been process.
|
private void |
leaveUnitaryOperator()
Leaves ternary operator (?:) and return tokens.
|
private NPathComplexityCheck.Values |
popValue()
Pops values from both stack of expression values and stack of range values.
|
private void |
pushValue(java.lang.Integer expressionValue)
Pushes the current range value on the range value stack.
|
void |
setMax(int max)
Setter to specify the maximum threshold allowed.
|
private void |
visitConditional(DetailAST ast,
int basicBranchingFactor)
Visits if, while, do-while, for and switch tokens - all of them have expression in
parentheses which is used for calculation.
|
void |
visitToken(DetailAST ast)
Called to process a token.
|
private void |
visitUnitaryOperator(DetailAST ast,
int basicBranchingFactor)
Visits ternary operator (?:) and return tokens.
|
clearViolations, destroy, finishTree, getFileContents, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, isCommentNodesRequired, log, log, log, setFileContents, setTabWidth, setTokensfinishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverityconfigure, contextualize, getConfiguration, setupChildpublic static final java.lang.String MSG_KEY
private static final int DEFAULT_MAX
private static final java.math.BigInteger INITIAL_VALUE
private final java.util.Deque<java.math.BigInteger> rangeValues
private final java.util.Deque<java.lang.Integer> expressionValues
private final java.util.Deque<java.lang.Boolean> afterValues
private final NPathComplexityCheck.TokenEnd processingTokenEnd
private java.math.BigInteger currentRangeValue
private int max
private boolean branchVisited
public NPathComplexityCheck()
public void setMax(int max)
max - the maximum thresholdpublic int[] getDefaultTokens()
AbstractCheckgetDefaultTokens in class AbstractCheckTokenTypespublic int[] getAcceptableTokens()
AbstractCheckgetAcceptableTokens in class AbstractCheckTokenTypespublic int[] getRequiredTokens()
AbstractCheckgetRequiredTokens in class AbstractCheckTokenTypespublic void beginTree(DetailAST rootAST)
AbstractCheckbeginTree in class AbstractCheckrootAST - the root of the treepublic void visitToken(DetailAST ast)
AbstractCheckvisitToken in class AbstractCheckast - the token to processpublic void leaveToken(DetailAST ast)
AbstractCheckleaveToken in class AbstractCheckast - the token leavingprivate void visitConditional(DetailAST ast, int basicBranchingFactor)
ast - visited token.basicBranchingFactor - default number of branches added.private void visitUnitaryOperator(DetailAST ast, int basicBranchingFactor)
ast - visited token.basicBranchingFactor - number of branches inherently added by this token.private void leaveUnitaryOperator()
private void leaveConditional()
private void leaveBranch()
private void leaveMethodDef(DetailAST ast)
ast - the token type representing the method definitionprivate void leaveAddingConditional()
private void pushValue(java.lang.Integer expressionValue)
expressionValue - value of expression calculated for current token.private NPathComplexityCheck.Values popValue()
private void leaveMultiplyingConditional()
private static int countConditionalOperators(DetailAST ast)
ast - inspected token.private static DetailAST getLastToken(DetailAST ast)
ast - the root of tree.private static int countCaseTokens(DetailAST ast)
ast - case group token.private static int countCaseConstants(DetailAST ast)
ast - switch rule token.Copyright © 2001-2022. All Rights Reserved.