Class NPathComplexityCheck
- All Implemented Interfaces:
Configurable
,Contextualizable
The NPATH metric computes the number of possible execution paths through a function(method). It takes into account the nesting of conditional statements and multipart 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) |
when[expr] | NP(expr) + 1 |
[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.
-
Property
max
- Specify the maximum threshold allowed. Type isint
. Default value is200
.
Parent is com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
-
npathComplexity
- Since:
- 3.4
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static final class
Coordinates of token end.private static final class
Class that store range value and expression value.Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
AbstractAutomaticBean.OutputStreamOptions
-
Field Summary
FieldsModifier and TypeFieldDescriptionStack of belongs to range values for question operator.private boolean
True, when branch is visited, but not leaved.private static final int[]
Tokens that are considered as case labels.private BigInteger
NP value for current range.private static final int
Default allowed complexity.Stack of NP values for expressions.private static final BigInteger
The initial current value.private int
Specify the maximum threshold allowed.static final String
A key is pointing to the warning message text in "messages.properties" file.private final NPathComplexityCheck.TokenEnd
Range of the last processed expression.private final Deque<BigInteger>
Stack of NP values for ranges. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoid
Called before the starting to process a tree.private static int
Counts number of case constants 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
Calculates number of conditional operators, including inline ternary operator, for a token.int[]
The configurable token set.int[]
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[]
The tokens that this check must be registered for.private void
Leaves catch.private void
Leaves else, default or case group tokens.private void
Leaves while, do, for, if, ternary (?private void
leaveMethodDef
(DetailAST ast) Process the end of a method definition.private void
Leaves try.void
leaveToken
(DetailAST ast) Called after all the child nodes have been process.private void
Leaves ternary operator (?private NPathComplexityCheck.Values
popValue()
Pops values from both stack of expression values and stack of range values.private void
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 (?private void
visitWhenExpression
(DetailAST ast, int basicBranchingFactor) Visits when expression token.Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
clearViolations, destroy, finishTree, getFileContents, getFilePath, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, isCommentNodesRequired, log, log, log, setFileContents, setTabWidth, setTokens
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
finishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverity
Methods inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
configure, contextualize, getConfiguration, setupChild
-
Field Details
-
MSG_KEY
A key is pointing to the warning message text in "messages.properties" file.- See Also:
-
CASE_LABEL_TOKENS
Tokens that are considered as case labels. -
DEFAULT_MAX
Default allowed complexity.- See Also:
-
INITIAL_VALUE
The initial current value. -
rangeValues
Stack of NP values for ranges. -
expressionValues
Stack of NP values for expressions. -
afterValues
Stack of belongs to range values for question operator. -
processingTokenEnd
Range of the last processed expression. Used for checking that ternary operation which is a part of expression won't be processed for second time. -
currentRangeValue
NP value for current range. -
max
Specify the maximum threshold allowed. -
branchVisited
True, when branch is visited, but not leaved.
-
-
Constructor Details
-
NPathComplexityCheck
public NPathComplexityCheck()
-
-
Method Details
-
setMax
Setter to specify the maximum threshold allowed.- Parameters:
max
- the maximum threshold- Since:
- 3.4
-
getDefaultTokens
Description copied from class:AbstractCheck
Returns the default token a check is interested in. Only used if the configuration for a check does not define the tokens.- Specified by:
getDefaultTokens
in classAbstractCheck
- Returns:
- the default tokens
- See Also:
-
getAcceptableTokens
Description copied from class:AbstractCheck
The configurable token set. Used to protect Checks against malicious users who specify an unacceptable token set in the configuration file. The default implementation returns the check's default tokens.- Specified by:
getAcceptableTokens
in classAbstractCheck
- Returns:
- the token set this check is designed for.
- See Also:
-
getRequiredTokens
Description copied from class:AbstractCheck
The tokens that this check must be registered for.- Specified by:
getRequiredTokens
in classAbstractCheck
- Returns:
- the token set this must be registered for.
- See Also:
-
beginTree
Description copied from class:AbstractCheck
Called before the starting to process a tree. Ideal place to initialize information that is to be collected whilst processing a tree.- Overrides:
beginTree
in classAbstractCheck
- Parameters:
rootAST
- the root of the tree
-
visitToken
Description copied from class:AbstractCheck
Called to process a token.- Overrides:
visitToken
in classAbstractCheck
- Parameters:
ast
- the token to process
-
leaveToken
Description copied from class:AbstractCheck
Called after all the child nodes have been process.- Overrides:
leaveToken
in classAbstractCheck
- Parameters:
ast
- the token leaving
-
visitConditional
Visits if, while, do-while, for and switch tokens - all of them have expression in parentheses which is used for calculation.- Parameters:
ast
- visited token.basicBranchingFactor
- default number of branches added.
-
visitWhenExpression
Visits when expression token. There is no guarantee that when expression will be bracketed, so we don't use visitConditional method.- Parameters:
ast
- visited token.basicBranchingFactor
- default number of branches added.
-
visitUnitaryOperator
Visits ternary operator (?:) and return tokens. They differ from those processed by visitConditional method in that their expression isn't bracketed.- Parameters:
ast
- visited token.basicBranchingFactor
- number of branches inherently added by this token.
-
leaveUnitaryOperator
Leaves ternary operator (?:) and return tokens. -
leaveConditional
Leaves while, do, for, if, ternary (?::), return or switch. -
leaveBranch
Leaves else, default or case group tokens. -
leaveMethodDef
Process the end of a method definition.- Parameters:
ast
- the token type representing the method definition
-
leaveAddingConditional
Leaves catch. -
pushValue
Pushes the current range value on the range value stack. Pushes this token expression value on the expression value stack.- Parameters:
expressionValue
- value of expression calculated for current token.
-
popValue
Pops values from both stack of expression values and stack of range values.- Returns:
- pair of head values from both of the stacks.
-
leaveMultiplyingConditional
Leaves try. -
countConditionalOperators
Calculates number of conditional operators, including inline ternary operator, for a token.- Parameters:
ast
- inspected token.- Returns:
- number of conditional operators.
- See Also:
-
getLastToken
Finds a leaf, which is the most distant from the root.- Parameters:
ast
- the root of tree.- Returns:
- the leaf.
-
countCaseTokens
Counts number of case tokens subject to a case group token.- Parameters:
ast
- case group token.- Returns:
- number of case tokens.
-
countCaseConstants
Counts number of case constants tokens in a switch labeled rule.- Parameters:
ast
- switch rule token.- Returns:
- number of case constant tokens.
-