Class CyclomaticComplexityCheck
- java.lang.Object
-
- com.puppycrawl.tools.checkstyle.api.AutomaticBean
-
- com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
-
- com.puppycrawl.tools.checkstyle.api.AbstractCheck
-
- com.puppycrawl.tools.checkstyle.checks.metrics.CyclomaticComplexityCheck
-
- All Implemented Interfaces:
Configurable
,Contextualizable
public class CyclomaticComplexityCheck extends AbstractCheck
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.
-
Property
max
- Specify the maximum threshold allowed. Type isint
. Default value is10
. -
Property
switchBlockAsSingleDecisionPoint
- Control whether to treat the whole switch block as a single decision point. Type isboolean
. Default value isfalse
. -
Property
tokens
- tokens to check Type isjava.lang.String[]
. Validation type istokenSet
. Default value is: LITERAL_WHILE, LITERAL_DO, LITERAL_FOR, LITERAL_IF, LITERAL_SWITCH, LITERAL_CASE, LITERAL_CATCH, QUESTION, LAND, LOR.
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 } }
Parent is
com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
-
cyclomaticComplexity
- Since:
- 3.2
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.api.AutomaticBean
AutomaticBean.OutputStreamOptions
-
-
Field Summary
Fields Modifier and Type Field Description static java.lang.String
MSG_KEY
A key is pointing to the warning message text in "messages.properties" file.
-
Constructor Summary
Constructors Constructor Description CyclomaticComplexityCheck()
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description int[]
getAcceptableTokens()
The configurable token set.int[]
getDefaultTokens()
Returns the default token a check is interested in.int[]
getRequiredTokens()
The tokens that this check must be registered for.void
leaveToken(DetailAST ast)
Called after all the child nodes have been process.void
setMax(int max)
Setter to specify the maximum threshold allowed.void
setSwitchBlockAsSingleDecisionPoint(boolean switchBlockAsSingleDecisionPoint)
Setter to control whether to treat the whole switch block as a single decision point.void
visitToken(DetailAST ast)
Called to process a token.-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
beginTree, clearMessages, destroy, finishTree, getFileContents, getLine, getLines, getMessages, getTabWidth, getTokenNames, 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.api.AutomaticBean
configure, contextualize, getConfiguration, setupChild
-
-
-
-
Field Detail
-
MSG_KEY
public static final java.lang.String MSG_KEY
A key is pointing to the warning message text in "messages.properties" file.- See Also:
- Constant Field Values
-
-
Method Detail
-
setSwitchBlockAsSingleDecisionPoint
public void setSwitchBlockAsSingleDecisionPoint(boolean switchBlockAsSingleDecisionPoint)
Setter to control whether to treat the whole switch block as a single decision point.- Parameters:
switchBlockAsSingleDecisionPoint
- whether to treat the whole switch block as a single decision point.
-
setMax
public final void setMax(int max)
Setter to specify the maximum threshold allowed.- Parameters:
max
- the maximum threshold
-
getDefaultTokens
public int[] 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:
TokenTypes
-
getAcceptableTokens
public int[] 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:
TokenTypes
-
getRequiredTokens
public final int[] 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:
TokenTypes
-
visitToken
public void visitToken(DetailAST ast)
Description copied from class:AbstractCheck
Called to process a token.- Overrides:
visitToken
in classAbstractCheck
- Parameters:
ast
- the token to process
-
leaveToken
public void leaveToken(DetailAST ast)
Description copied from class:AbstractCheck
Called after all the child nodes have been process.- Overrides:
leaveToken
in classAbstractCheck
- Parameters:
ast
- the token leaving
-
-