From 402a50e72f6d35c1a2a495af7d10be726823bcf4 Mon Sep 17 00:00:00 2001 From: Mike Poage Date: Mon, 13 Feb 2023 08:40:02 -0500 Subject: [PATCH 1/4] update checkstyle to version 10.7.0 --- CHECKSTYLE_VERSION | 2 +- Dockerfile | 6 +- bin/install-checkstyle.sh | 2 +- check_contents.yml | 173 ++++++++++++++++-------------- config/codeclimate_checkstyle.xml | 1 - 5 files changed, 100 insertions(+), 84 deletions(-) diff --git a/CHECKSTYLE_VERSION b/CHECKSTYLE_VERSION index 803ed03..1bcdaf5 100644 --- a/CHECKSTYLE_VERSION +++ b/CHECKSTYLE_VERSION @@ -1 +1 @@ -8.39 +10.7.0 diff --git a/Dockerfile b/Dockerfile index 1be881b..c8c902e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -20,12 +20,12 @@ ENV JAVA_HOME /usr/lib/jvm/java-1.8-openjdk/jre ENV PATH $PATH:/usr/lib/jvm/java-1.8-openjdk/jre/bin:/usr/lib/jvm/java-1.8-openjdk/bin ENV JAVA_VERSION 8u252 -ENV JAVA_ALPINE_VERSION 8.275.01-r0 +ENV JAVA_ALPINE_VERSION 11.0.4_p4-r1 RUN set -x \ && apk update && apk add --no-cache --update \ - openjdk8-jre="$JAVA_ALPINE_VERSION" \ - && [ "$JAVA_HOME" = "$(docker-java-home)" ] + openjdk11-jre="$JAVA_ALPINE_VERSION" + # && [ "$JAVA_HOME" = "$(docker-java-home)" ] WORKDIR /usr/src/app diff --git a/bin/install-checkstyle.sh b/bin/install-checkstyle.sh index 7f8b316..3ab4885 100755 --- a/bin/install-checkstyle.sh +++ b/bin/install-checkstyle.sh @@ -1,7 +1,7 @@ #!/bin/sh # use `make upgrade` to update this URL to the latest version -URL='https://github.com/checkstyle/checkstyle/releases/download/checkstyle-8.39/checkstyle-8.39-all.jar' +URL='https://github.com/checkstyle/checkstyle/releases/download/checkstyle-10.7.0/checkstyle-10.7.0-all.jar' wget -O /usr/local/bin/checkstyle.jar $URL diff --git a/check_contents.yml b/check_contents.yml index 84d24b0..5e4fc72 100644 --- a/check_contents.yml +++ b/check_contents.yml @@ -13,13 +13,13 @@ com.puppycrawl.tools.checkstyle.checks.annotation.AnnotationOnSameLineCheck: Package: com.puppycrawl.tools.checkstyle.checks.annotation com.puppycrawl.tools.checkstyle.checks.annotation.AnnotationUseStyleCheck: Description: | -

Checks the style of elements in annotations.

Annotations have three element styles starting with the least verbose.

To not enforce an element style a ElementStyleOption.IGNORE type is provided.The desired style can be set through the elementStyle property.

Using the ElementStyleOption.EXPANDED style is more verbose.The expanded version is sometimes referred to as "named parameters" in other languages.

Using the ElementStyleOption.COMPACT style is less verbose.This style can only be used when there is an element called 'value' which is eitherthe sole element or all other elements have default values.

Using the ElementStyleOption.COMPACT_NO_ARRAY style is less verbose.It is similar to the ElementStyleOption.COMPACT style but single value arraysare flagged.With annotations a single value array does not need to be placed in an array initializer.

The ending parenthesis are optional when using annotations with no elements.To always require ending parenthesis use the ClosingParensOption.ALWAYS type.To never have ending parenthesis use the ClosingParensOption.NEVER type.To not enforce a closing parenthesis preference a ClosingParensOption.IGNOREtype is provided. Set this through the closingParens property.

Annotations also allow you to specify arrays of elements in a standard format.As with normal arrays, a trailing comma is optional.To always require a trailing comma use the TrailingArrayCommaOption.ALWAYStype.To never have a trailing comma use the TrailingArrayCommaOption.NEVER type.To not enforce a trailing array comma preference aTrailingArrayCommaOption.IGNORE type is provided.Set this through the trailingArrayComma property.

By default the ElementStyleOption is set to COMPACT_NO_ARRAY,the TrailingArrayCommaOption is set to NEVER,and the ClosingParensOption is set to NEVER.

According to the JLS, it is legal to include a trailing commain arrays used in annotations but Sun's Java 5 & 6 compilers will notcompile with this syntax. This may in be a bug in Sun's compilerssince eclipse 3.4's built-in compiler does allow this syntax asdefined in the JLS. Note: this was tested with compilers included withJDK versions 1.5.0.17 and 1.6.0.11 and the compiler included with eclipse 3.4.1.

See Java Language specification, §9.7.

+

Checks the style of elements in annotations.

Annotations have three element styles starting with the least verbose.

To not enforce an element style a ElementStyleOption.IGNORE type is provided.The desired style can be set through the elementStyle property.

Using the ElementStyleOption.EXPANDED style is more verbose.The expanded version is sometimes referred to as "named parameters" in other languages.

Using the ElementStyleOption.COMPACT style is less verbose.This style can only be used when there is an element called 'value' which is eitherthe sole element or all other elements have default values.

Using the ElementStyleOption.COMPACT_NO_ARRAY style is less verbose.It is similar to the ElementStyleOption.COMPACT style but single value arraysare flagged.With annotations a single value array does not need to be placed in an array initializer.

The ending parenthesis are optional when using annotations with no elements.To always require ending parenthesis use the ClosingParensOption.ALWAYS type.To never have ending parenthesis use the ClosingParensOption.NEVER type.To not enforce a closing parenthesis preference a ClosingParensOption.IGNOREtype is provided. Set this through the closingParens property.

Annotations also allow you to specify arrays of elements in a standard format.As with normal arrays, a trailing comma is optional.To always require a trailing comma use the TrailingArrayCommaOption.ALWAYStype.To never have a trailing comma use the TrailingArrayCommaOption.NEVER type.To not enforce a trailing array comma preference aTrailingArrayCommaOption.IGNORE type is provided.Set this through the trailingArrayComma property.

By default, the ElementStyleOption is set to COMPACT_NO_ARRAY,the TrailingArrayCommaOption is set to NEVER,and the ClosingParensOption is set to NEVER.

According to the JLS, it is legal to include a trailing commain arrays used in annotations but Sun's Java 5 & 6 compilers will notcompile with this syntax. This may in be a bug in Sun's compilerssince eclipse 3.4's built-in compiler does allow this syntax asdefined in the JLS. Note: this was tested with compilers included withJDK versions 1.5.0.17 and 1.6.0.11 and the compiler included with eclipse 3.4.1.

See Java Language specification, §9.7.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.annotation com.puppycrawl.tools.checkstyle.checks.annotation.MissingDeprecatedCheck: Description: | -

Verifies that the annotation @Deprecated and the Javadoc tag@deprecated are both present when either of them is present.

Both ways of flagging deprecation serve their own purpose.The @Deprecated annotation is used for compilers and development tools.The @deprecated javadoc tag is used to document why something is deprecatedand what, if any, alternatives exist.

In order to properly mark something as deprecated both forms ofdeprecation should be present.

Package deprecation is a exception to the rule of always using thejavadoc tag and annotation to deprecate. It is not clear if thejavadoc tool will support it or not as newer versions keep flip floppingon if it is supported or will cause an error.See JDK-8160601.The deprecated javadoc tag is currently the only way to say why the packageis deprecated and what to use instead. Until this is resolved, if youdon't want to print violations on package-info, you can use afilter to ignore these files untilthe javadoc tool faithfully supports it. An example config usingSuppressionSingleFilter is:


<!-- required till https://bugs.openjdk.java.net/browse/JDK-8160601 -->
<module name="SuppressionSingleFilter">
<property name="checks" value="MissingDeprecatedCheck"/>
<property name="files" value="package-info\.java"/>
</module>

+

Verifies that the annotation @Deprecated and the Javadoc tag@deprecated are both present when either of them is present.

Both ways of flagging deprecation serve their own purpose.The @Deprecated annotation is used for compilers and development tools.The @deprecated javadoc tag is used to document why something is deprecatedand what, if any, alternatives exist.

In order to properly mark something as deprecated both forms ofdeprecation should be present.

Package deprecation is an exception to the rule of always using thejavadoc tag and annotation to deprecate. It is not clear if thejavadoc tool will support it or not as newer versions keep flip-floppingon if it is supported or will cause an error.See JDK-8160601.The deprecated javadoc tag is currently the only way to say why the packageis deprecated and what to use instead. Until this is resolved, if youdon't want to print violations on package-info, you can use afilter to ignore these files untilthe javadoc tool faithfully supports it. An example config usingSuppressionSingleFilter is:


<!-- required till https://bugs.openjdk.org/browse/JDK-8160601 -->
<module name="SuppressionSingleFilter">
<property name="checks" value="MissingDeprecatedCheck"/>
<property name="files" value="package-info\.java"/>
</module>

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.annotation @@ -43,25 +43,25 @@ com.puppycrawl.tools.checkstyle.checks.annotation.SuppressWarningsCheck: Package: com.puppycrawl.tools.checkstyle.checks.annotation com.puppycrawl.tools.checkstyle.checks.SuppressWarningsHolderCheck: Description: | -

Maintains a set of check suppressions from@SuppressWarnings annotations. It allows toprevent Checkstyle from reporting violations from parts of codethat were annotated with @SuppressWarnings andusing name of the check to be excluded. You can also definealiases for check names that need to be suppressed.

+

Maintains a set of check suppressions from@SuppressWarnings annotations. It allows toprevent Checkstyle from reporting violations from parts of codethat were annotated with @SuppressWarnings andusing name of the check to be excluded. It is possible to suppressall the checkstyle warnings with the argument"all".You can also use a checkstyle: prefix to prevent compiler fromprocessing these annotations. You can also definealiases for check names that need to be suppressed.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.blocks.AvoidNestedBlocksCheck: Description: | -

Finds nested blocks (blocks that are used freely in the code).

Rationale: Nested blocks are often leftovers from thedebugging process, they confuse the reader.

For example this Check finds the obsolete braces in


public void guessTheOutput()
{
int whichIsWhich = 0;
{
whichIsWhich = 2;
}
System.out.println("value = " + whichIsWhich);
}

and debugging / refactoring leftovers such as


// if (conditionThatIsNotUsedAnyLonger)
{
System.out.println("unconditional");
}

A case in a switch statement does not implicitly form a block.Thus to be able to introduce local variables that have casescope it is necessary to open a nested block. This issupported, set the allowInSwitchCase property to true andinclude all statements of the case in the block.


switch (a)
{
case 0:
// Never OK, break outside block
{
x = 1;
}
break;
case 1:
// Never OK, statement outside block
System.out.println("Hello");
{
x = 2;
break;
}
case 2:
// OK if allowInSwitchCase is true
{
System.out.println("Hello");
x = 3;
break;
}
}

+

Finds nested blocks (blocks that are used freely in the code).

Rationale: Nested blocks are often leftovers from thedebugging process, they confuse the reader.

For example, this check finds the obsolete braces in


public void guessTheOutput()
{
int whichIsWhich = 0;
{
whichIsWhich = 2;
}
System.out.println("value = " + whichIsWhich);
}

and debugging / refactoring leftovers such as


// if (conditionThatIsNotUsedAnyLonger)
{
System.out.println("unconditional");
}

A case in a switch statement does not implicitly form a block.Thus, to be able to introduce local variables that have casescope it is necessary to open a nested block. This issupported, set the allowInSwitchCase property to true andinclude all statements of the case in the block.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.blocks com.puppycrawl.tools.checkstyle.checks.blocks.EmptyBlockCheck: Description: | -

Checks for empty blocks. This check does not validate sequential blocks.

Sequential blocks won't be checked. Also, no violations for fallthrough:


switch (a) {
case 1: // no violation
case 2: // no violation
case 3: someMethod(); { } // no violation
default: break;
}

NOTE: This check processes LITERAL_CASE and LITERAL_DEFAULT separately.Verification empty block is done for single most nearest {@code case} or {@code default}.

+

Checks for empty blocks. This check does not validate sequential blocks.

Sequential blocks won't be checked. Also, no violations for fallthrough:


switch (a) {
case 1: // no violation
case 2: // no violation
case 3: someMethod(); { } // no violation
default: break;
}

NOTE: This check processes LITERAL_CASE and LITERAL_DEFAULT separately.Verification empty block is done for single nearest {@code case} or {@code default}.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.blocks com.puppycrawl.tools.checkstyle.checks.blocks.EmptyCatchBlockCheck: Description: | -

Checks for empty catch blocks.By default check allows empty catch block with any comment inside.

+

Checks for empty catch blocks.By default, check allows empty catch block with any comment inside.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.blocks @@ -91,7 +91,7 @@ com.puppycrawl.tools.checkstyle.checks.coding.ArrayTrailingCommaCheck: Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.AvoidDoubleBraceInitializationCheck: Description: | -

Detects double brace initialization.

Rationale: Double brace initialization (set ofInstance Initializers in class body) may look cool,but it is considered as anti-pattern and should be avoided.This is also can lead to a hard-to-detect memory leak, if the anonymous class instance isreturned outside and other object(s) hold reference to it.Created anonymous class is not static, it holds an implicit reference to the outer classinstance.See thisblog post andarticle for more details.Check ignores any comments and semicolons in class body.

+

Detects double brace initialization.

Rationale: Double brace initialization (set ofInstance Initializers in class body) may look cool,but it is considered as anti-pattern and should be avoided.This is also can lead to a hard-to-detect memory leak, if the anonymous class instance isreturned outside and other object(s) hold reference to it.Created anonymous class is not static, it holds an implicit reference to the outer classinstance.See thisblog post andarticle for more details.Check ignores any comments and semicolons in class body.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.coding @@ -151,7 +151,7 @@ com.puppycrawl.tools.checkstyle.checks.coding.ExplicitInitializationCheck: Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.FallThroughCheck: Description: | -

Checks for fall-through in switchstatements. Finds locations where a casecontains Java code but lacks a break, return,throw or continuestatement.

The check honors special comments to suppress the warning.By default the texts"fallthru", "fall thru", "fall-thru","fallthrough", "fall through", "fall-through""fallsthrough", "falls through", "falls-through" (case sensitive).The comment containing these words must be all on one line,and must be on the last non-empty line before thecase triggering the warning or onthe same line before the case(ugly, but possible).

Note: The check assumes that there is no unreachablecode in the case.

+

Checks for fall-through in switchstatements. Finds locations where a casecontains Java code but lacks a break, return,yield, throw or continuestatement.

The check honors special comments to suppress the warning.By default, the texts"fallthru", "fall thru", "fall-thru","fallthrough", "fall through", "fall-through""fallsthrough", "falls through", "falls-through" (case-sensitive).The comment containing these words must be all on one line,and must be on the last non-empty line before thecase triggering the warning or onthe same line before the case(ugly, but possible).

Note: The check assumes that there is no unreachablecode in the case.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.coding @@ -187,13 +187,13 @@ com.puppycrawl.tools.checkstyle.checks.coding.IllegalThrowsCheck: Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.IllegalTokenCheck: Description: | -

Checks for illegal tokens. By default labels are prohibited.

Rationale: Certain language features can harm readability, lead toconfusion or are not obvious to novice developers. Other featuresmay be discouraged in certain frameworks, such as not havingnative methods in Enterprise JavaBeans components.

+

Checks for illegal tokens. By default, labels are prohibited.

Rationale: Certain language features can harm readability, lead toconfusion or are not obvious to novice developers. Other featuresmay be discouraged in certain frameworks, such as not havingnative methods in Enterprise JavaBeans components.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.IllegalTokenTextCheck: Description: | -

Checks specified tokens text for matching an illegal pattern.By default no tokens are specified.

+

Checks specified tokens text for matching an illegal pattern.By default, no tokens are specified.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.coding @@ -205,7 +205,7 @@ com.puppycrawl.tools.checkstyle.checks.coding.IllegalTypeCheck: Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.InnerAssignmentCheck: Description: | -

Checks for assignments in subexpressions, such as inString s = Integer.toString(i = 2);.

Rationale: With the exception of loop idioms,all assignments should occur in their own top-level statementto increase readability. With inner assignments like the one given above, it is difficultto see all places where a variable is set.

Note: Check allows usage of the popular assignments in loops:


String line;
while ((line = bufferedReader.readLine()) != null) { // OK
// process the line
}

for (;(line = bufferedReader.readLine()) != null;) { // OK
// process the line
}

do {
// process the line
}
while ((line = bufferedReader.readLine()) != null); // OK

Assignment inside a condition is not a problem here, as the assignment is surrounded byan extra pair of parentheses. The comparison is != null and there is nochance that intention was to write line == reader.readLine().

+

Checks for assignments in subexpressions, such as inString s = Integer.toString(i = 2);.

Rationale: Except for the loop idioms,all assignments should occur in their own top-level statementto increase readability. With inner assignments like the one given above, it is difficultto see all places where a variable is set.

Note: Check allows usage of the popular assignments in loops:


String line;
while ((line = bufferedReader.readLine()) != null) { // OK
// process the line
}

for (;(line = bufferedReader.readLine()) != null;) { // OK
// process the line
}

do {
// process the line
}
while ((line = bufferedReader.readLine()) != null); // OK

Assignment inside a condition is not a problem here, as the assignment is surrounded byan extra pair of parentheses. The comparison is != null and there is nochance that intention was to write line == reader.readLine().

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.coding @@ -217,7 +217,7 @@ com.puppycrawl.tools.checkstyle.checks.coding.MagicNumberCheck: Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.MatchXpathCheck: Description: | -

Evaluates Xpath query and report violation on all matching AST nodes. This check allowsuser to implement custom checks using Xpath. If Xpath query is not specified explicitly,then the check does nothing.

It is recommended to define custom message for violation to explain what is not allowedand what to use instead, default message might be too abstract. To customize a messageyou need to add message element with matchxpath.match askey attribute and desired message as value attribute.

Please read more about Xpath syntax atXpath Syntax.Information regarding Xpath functions can be found atXSLT/XPathReference. Note, that @text attribute can used only with token types thatare listed inXpathUtil.

+

Evaluates Xpath query and report violation on all matching AST nodes. This check allowsuser to implement custom checks using Xpath. If Xpath query is not specified explicitly,then the check does nothing.

It is recommended to define custom message for violation to explain what is not allowedand what to use instead, default message might be too abstract. To customize a messageyou need to add message element with matchxpath.match askey attribute and desired message as value attribute.

Please read more about Xpath syntax atXpath Syntax.Information regarding Xpath functions can be found atXSLT/XPathReference. Note, that @text attribute can be used only with token types thatare listed inXpathUtil.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.coding @@ -229,13 +229,13 @@ com.puppycrawl.tools.checkstyle.checks.coding.MissingCtorCheck: Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.MissingSwitchDefaultCheck: Description: | -

Checks that switch statement has a default clause.

Rationale: It's usually a good idea to introduce a default case inevery switch statement. Even if the developer is sure that allcurrently possible cases are covered, this should be expressed inthe default branch, e.g. by using an assertion. This way the code isprotected against later changes, e.g. introduction of new types in anenumeration type. Note that the compiler requires switch expressionsto be exhaustive, so this check does not enforce default branches onsuch expressions.

+

Checks that switch statement has a default clause.

Rationale: It's usually a good idea to introduce a default case inevery switch statement. Even if the developer is sure that allcurrently possible cases are covered, this should be expressed inthe default branch, e.g. by using an assertion. This way the code isprotected against later changes, e.g. introduction of new types in anenumeration type.

This check does not validate any switch expressions. Rationale:The compiler requires switch expressions to be exhaustive. This meansthat all possible inputs must be covered.

This check does not validate switch statements that use pattern or nulllabels. Rationale: Switch statements that use pattern or null labels arechecked by the compiler for exhaustiveness. This means that all possibleinputs must be covered.

See theJava Language Specification for more information about switch statementsand expressions.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.ModifiedControlVariableCheck: Description: | -

Checks that for loop control variables are not modified insidethe for block. An example is:


for (int i = 0; i < 1; i++) {
i++; //violation
}

Rationale: If the control variable is modified inside the loopbody, the program flow becomes more difficult to follow. SeeFOR statement specification for more details.

Such loop would be suppressed:


for (int i = 0; i < 10;) {
i++;
}

+

Checks that for loop control variables are not modified insidethe for block. An example is:


for (int i = 0; i < 1; i++) {
i++; // violation
}

Rationale: If the control variable is modified inside the loopbody, the program flow becomes more difficult to follow. SeeFOR statement specification for more details.

Such loop would be suppressed:


for (int i = 0; i < 10;) {
i++;
}

NOTE:The check works with only primitive type variables.The check will not work for arrays used as control variable.An example is


for (int a[]={0};a[0] < 10;a[0]++) {
a[0]++; // it will skip this violation
}

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.coding @@ -277,7 +277,7 @@ com.puppycrawl.tools.checkstyle.checks.coding.NoArrayTrailingCommaCheck: Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.NoCloneCheck: Description: | -

Checks that the clone method is not overridden from theObject class.

This check is almost exactly the same as the NoFinalizerCheck.

See Object.clone()

Rationale: The clone method relies on strange, hard to follow rules thatare difficult to get right and do not work in all situations.In some cases, either a copy constructoror a static factory method can be used instead of the clone methodto return copies of an object.For more information on rules for the clone method and its issues, see Effective Java:Programming Language Guide First Edition by Joshua Blochpages 45-52.

Below are some of the rules/reasons why the clone method should be avoided.

Two alternatives to the clone method, in some cases, is a copy constructor or a staticfactory method to return copies of an object. Both of these approaches are simpler anddo not conflict with final fields. They do not force the calling client to handle aCloneNotSupportedException. They also are typed therefore no casting is necessary.Finally, they are more flexible since they can take interface types rather than concreteclasses.

Sometimes a copy constructor or static factory is not an acceptable alternative to theclone method. The example below highlights the limitation of a copy constructor(or static factory). Assume Square is a subclass for Shape.


Shape s1 = new Square();
System.out.println(s1 instanceof Square); //true

...assume at this point the code knows nothing of s1 being a Square that's the beautyof polymorphism but the code wants to copy the Square which is declared as a Shape,its super type...


Shape s2 = new Shape(s1); //using the copy constructor
System.out.println(s2 instanceof Square); //false

The working solution (without knowing about all subclasses and doing many casts) is to dothe following (assuming correct clone implementation).


Shape s2 = s1.clone();
System.out.println(s2 instanceof Square); //true

Just keep in mind if this type of polymorphic cloning is required then a properlyimplemented clone method may be the best choice.

Much of this information was taken from Effective Java: Programming Language Guide FirstEdition by Joshua Bloch pages 45-52. Give Bloch credit for writing an excellent book.

+

Checks that the clone method is not overridden from theObject class.

This check is almost exactly the same as the NoFinalizerCheck.

See Object.clone()

Rationale: The clone method relies on strange, hard to follow rules thatare difficult to get right and do not work in all situations.In some cases, either a copy constructoror a static factory method can be used instead of the clone methodto return copies of an object.For more information on rules for the clone method and its issues, see Effective Java:Programming Language Guide First Edition by Joshua Blochpages 45-52.

Below are some rules/reasons why the clone method should be avoided.

Two alternatives to the clone method, in some cases, is a copy constructor or a staticfactory method to return copies of an object. Both of these approaches are simpler anddo not conflict with final fields. They do not force the calling client to handle aCloneNotSupportedException. They also are typed therefore no casting is necessary.Finally, they are more flexible since they can take interface types rather than concreteclasses.

Sometimes a copy constructor or static factory is not an acceptable alternative to theclone method. The example below highlights the limitation of a copy constructor(or static factory). Assume Square is a subclass for Shape.


Shape s1 = new Square();
System.out.println(s1 instanceof Square); //true

...assume at this point the code knows nothing of s1 being a Square that's the beautyof polymorphism but the code wants to copy the Square which is declared as a Shape,its super type...


Shape s2 = new Shape(s1); //using the copy constructor
System.out.println(s2 instanceof Square); //false

The working solution (without knowing about all subclasses and doing many casts) is to dothe following (assuming correct clone implementation).


Shape s2 = s1.clone();
System.out.println(s2 instanceof Square); //true

Just keep in mind if this type of polymorphic cloning is required then a properlyimplemented clone method may be the best choice.

Much of this information was taken from Effective Java: Programming Language Guide FirstEdition by Joshua Bloch pages 45-52. Give Bloch credit for writing an excellent book.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.coding @@ -331,7 +331,7 @@ com.puppycrawl.tools.checkstyle.checks.coding.ReturnCountCheck: Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.SimplifyBooleanExpressionCheck: Description: | -

Checks for over-complicated boolean expressions. Currently findscode like if (b == true), b || true, !false,etc.

Rationale: Complex boolean logic makes code hard to understand andmaintain.

+

Checks for over-complicated boolean expressions. Currently, it findscode like if (b == true), b || true, !false,boolean a = q > 12 ? true : false,etc.

Rationale: Complex boolean logic makes code hard to understand andmaintain.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.coding @@ -343,7 +343,7 @@ com.puppycrawl.tools.checkstyle.checks.coding.SimplifyBooleanReturnCheck: Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.StringLiteralEqualityCheck: Description: | -

Checks that string literals are not used with == or!=.Since == will compare the object references,not the actual value of the strings,String.equals() should be used.More information can be foundin this article.

Rationale: Novice Java programmers often use code like:


if (x == "something")

when they mean


if ("something".equals(x))

+

Checks that string literals are not used with == or!=.Since == will compare the object references,not the actual value of the strings,String.equals() should be used.More information can be foundin this article.

Rationale: Novice Java programmers often use code like:


if (x == "something")

when they mean


if ("something".equals(x))

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.coding @@ -361,7 +361,7 @@ com.puppycrawl.tools.checkstyle.checks.coding.SuperFinalizeCheck: Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.UnnecessaryParenthesesCheck: Description: | -

Checks if unnecessary parentheses are used in a statement or expression.The check will flag the following with warnings:


return (x); // parens around identifier
return (x + 1); // parens around return value
int x = (y / 2 + 1); // parens around assignment rhs
for (int i = (0); i < 10; i++) { // parens around literal
t -= (z + 1); // parens around assignment rhs

+

Checks if unnecessary parentheses are used in a statement or expression.The check will flag the following with warnings:


return (x); // parens around identifier
return (x + 1); // parens around return value
int x = (y / 2 + 1); // parens around assignment rhs
for (int i = (0); i < 10; i++) { // parens around literal
t -= (z + 1); // parens around assignment rhs
boolean a = (x > 7 && y > 5) // parens around expression
|| z < 9;
boolean b = (~a) > -27 // parens around ~a
&& (a-- < 30); // parens around expression

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.coding @@ -389,9 +389,15 @@ com.puppycrawl.tools.checkstyle.checks.coding.UnnecessarySemicolonInTryWithResou This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.coding +com.puppycrawl.tools.checkstyle.checks.coding.UnusedLocalVariableCheck: + Description: | +

Checks that a local variable is declared and/or assigned, but not used.Doesn't support pattern variables yet.Doesn't check array components as arraycomponents are classified as different kind of variables by JLS.

+ This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project. +

+ Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.VariableDeclarationUsageDistanceCheck: Description: | -

Checks the distance between declaration of variable and its first usage.

+

Checks the distance between declaration of variable and its first usage.Note : Variable declaration/initialization statements are not countedwhile calculating length.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.coding @@ -403,13 +409,13 @@ com.puppycrawl.tools.checkstyle.checks.design.DesignForExtensionCheck: Package: com.puppycrawl.tools.checkstyle.checks.design com.puppycrawl.tools.checkstyle.checks.design.FinalClassCheck: Description: | -

Checks that a class which has only private constructors is declaredas final. Doesn't check for classes nested in interfacesor annotations, as they are always final there.

+

Checks that a class that has only private constructors andhas no descendant classes is declared as final.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.design com.puppycrawl.tools.checkstyle.checks.design.HideUtilityClassConstructorCheck: Description: | -

Makes sure that utility classes (classes that contain only staticmethods or fields in their API) do not have a public constructor.

Rationale: Instantiating utility classes does not make sense. Hencethe constructors should either be private or (if you want to allowsubclassing) protected. A common mistake is forgetting to hide thedefault constructor.

If you make the constructor protected you may want to consider thefollowing constructor implementation technique to disallowinstantiating subclasses:


public class StringUtils // not final to allow subclassing
{
protected StringUtils() {
// prevents calls from subclass
throw new UnsupportedOperationException();
}

public static int count(char c, String s) {
// ...
}
}

+

Makes sure that utility classes (classes that contain only staticmethods or fields in their API) do not have a public constructor.

Rationale: Instantiating utility classes does not make sense. Hence,the constructors should either be private or (if you want to allowsubclassing) protected. A common mistake is forgetting to hide thedefault constructor.

If you make the constructor protected you may want to consider thefollowing constructor implementation technique to disallowinstantiating subclasses:


public class StringUtils // not final to allow subclassing
{
protected StringUtils() {
// prevents calls from subclass
throw new UnsupportedOperationException();
}

public static int count(char c, String s) {
// ...
}
}

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.design @@ -427,13 +433,13 @@ com.puppycrawl.tools.checkstyle.checks.design.InterfaceIsTypeCheck: Package: com.puppycrawl.tools.checkstyle.checks.design com.puppycrawl.tools.checkstyle.checks.design.MutableExceptionCheck: Description: | -

Ensures that exception classes (classes with names conforming to some regularexpression and explicitly extending classes with names conforming to otherregular expression) are immutable, that is, that they have only final fields.

The current algorithm is very simple: it checks that all members ofexception are final. The user can still mutate an exception's instance(e.g. Throwable has a method called setStackTracewhich changes the exception's stack trace). But, at least, all informationprovided by this exception type is unchangeable.

Rationale: Exception instances should represent an errorcondition. Having non final fields not only allows the state to bemodified by accident and therefore mask the original condition butalso allows developers to accidentally forget to set the initial state.In both cases, code catching the exception could draw incorrectconclusions based on the state.

+

Ensures that exception classes (classes with names conforming to some patternand explicitly extending classes with names conforming to otherpattern) are immutable, that is, that they have only final fields.

The current algorithm is very simple: it checks that all members ofexception are final. The user can still mutate an exception's instance(e.g. Throwable has a method called setStackTracewhich changes the exception's stack trace). But, at least, all informationprovided by this exception type is unchangeable.

Rationale: Exception instances should represent an errorcondition. Having non-final fields not only allows the state to bemodified by accident and therefore mask the original condition butalso allows developers to accidentally forget to set the initial state.In both cases, code catching the exception could draw incorrectconclusions based on the state.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.design com.puppycrawl.tools.checkstyle.checks.design.OneTopLevelClassCheck: Description: | -

Checks that each top-level class, interface, enumor annotation resides in a source file of its own.Official description of a 'top-level' term:7.6. Top Level Type Declarations.If file doesn't contains public class, interface, enum or annotation,top-level type is the first type in file.

+

Checks that each top-level class, interface, enumor annotation resides in a source file of its own.Official description of a 'top-level' term:7.6. Top Level Type Declarations.If file doesn't contain public class, interface, enum or annotation,top-level type is the first type in file.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.design @@ -445,13 +451,13 @@ com.puppycrawl.tools.checkstyle.checks.design.ThrowsCountCheck: Package: com.puppycrawl.tools.checkstyle.checks.design com.puppycrawl.tools.checkstyle.checks.design.VisibilityModifierCheck: Description: | -

Checks visibility of class members. Only static final, immutable or annotatedby specified annotation members may be public; other class members must be privateunless the property protectedAllowed or packageAllowed is set.

Public members are not flagged if the name matches the publicmember regular expression (contains "^serialVersionUID$" by default).

Note thatCheckstyle 2 used to include "^f[A-Z][a-zA-Z0-9]*$" in the defaultpattern to allow names used in container-managed persistence for Enterprise JavaBeans(EJB) 1.1 with the default settings. With EJB 2.0 it is no longer necessary to havepublic access for persistent fields, so the default has been changed.

Rationale: Enforce encapsulation.

Check also has options making it less strict:

ignoreAnnotationCanonicalNames - the list of annotations which ignore variablesin consideration. If user will provide short annotation name that type will match to anynamed the same type without consideration of package.

allowPublicFinalFields - which allows public final fields.

allowPublicImmutableFields - which allows immutable fields to be declared aspublic if defined in final class.

Field is known to be immutable if:

Classes known to be immutable are listed in immutableClassCanonicalNames by theircanonical names.

Property Rationale: Forcing all fields of class to have private modifier by default isgood in most cases, but in some cases it drawbacks in too much boilerplate get/set code.One of such cases are immutable classes.

Restriction: Check doesn't check if class is immutable, there's nochecking if accessory methods are missing and all fields are immutable, we only checkif current field is immutable or final. Under the flagallowPublicImmutableFields, the enclosing class must also be final, to encourageimmutability. Under the flag allowPublicFinalFields, the final modifier onthe enclosing class is optional.

Star imports are out of scope of this Check. So if one of type imported viastar import collides with user specified one by its short name -there won't be Check's violation.

+

Checks visibility of class members. Only static final, immutable or annotatedby specified annotation members may be public; other class members must be privateunless the property protectedAllowed or packageAllowed is set.

Public members are not flagged if the name matches the publicmember regular expression (contains "^serialVersionUID$" by default).

Note thatCheckstyle 2 used to include "^f[A-Z][a-zA-Z0-9]*$" in the defaultpattern to allow names used in container-managed persistence for Enterprise JavaBeans(EJB) 1.1 with the default settings. With EJB 2.0 it is no longer necessary to havepublic access for persistent fields, so the default has been changed.

Rationale: Enforce encapsulation.

Check also has options making it less strict:

ignoreAnnotationCanonicalNames - the list of annotations which ignore variablesin consideration. If user want to provide short annotation name that typewill match to any named the same type without consideration of package.

allowPublicFinalFields - which allows public final fields.

allowPublicImmutableFields - which allows immutable fields to be declared aspublic if defined in final class.

Field is known to be immutable if:

Classes known to be immutable are listed in immutableClassCanonicalNames by theircanonical names.

Property Rationale: Forcing all fields of class to have private modifier by default isgood in most cases, but in some cases it drawbacks in too much boilerplate get/set code.One of such cases are immutable classes.

Restriction: Check doesn't check if class is immutable, there's nochecking if accessory methods are missing and all fields are immutable, we only checkif current field is immutable or final. Under the flagallowPublicImmutableFields, the enclosing class must also be final, to encourageimmutability. Under the flag allowPublicFinalFields, the final modifier onthe enclosing class is optional.

Star imports are out of scope of this Check. So if one of type imported viastar import collides with user specified one by its short name -there won't be Check's violation.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.design com.puppycrawl.tools.checkstyle.filefilters.BeforeExecutionExclusionFileFilterCheck: Description: | -

File filter BeforeExecutionExclusionFileFilter decides which files should beexcluded from being processed by the utility.

By default Checkstyle includes all files and sub-directories in a directory to beprocessed and checked for violations. Users could have files that are in thesesub-directories that shouldn't be processed with their checkstyle configuration forvarious reasons, one of which is a valid Java file that won't pass Checkstyle's parser.When Checkstyle tries to parse a Java file and fails, it will throw anException and halt parsing any more files for violations. An example of avalid Java file Checkstyle can't parse is JDK 9's module-info.java.This file filter will exclude these problem files from being parsed,allowing the rest of the files to run normal and be validated.

Note: When a file is excluded from the utility, it is excluded from all Checks andno testing for violations will be performed on them.

+

File filter BeforeExecutionExclusionFileFilter decides which files should beexcluded from being processed by the utility.

By default, Checkstyle includes all files and subdirectories in a directory to beprocessed and checked for violations. Users could have files that are in thesesubdirectories that shouldn't be processed with their checkstyle configuration forvarious reasons, one of which is a valid Java file that won't pass Checkstyle's parser.When Checkstyle tries to parse a Java file and fails, it will throw anException and halt parsing any more files for violations. An example of avalid Java file Checkstyle can't parse is JDK 9's module-info.java.This file filter will exclude these problem files from being parsed,allowing the rest of the files to run normal and be validated.

Note: When a file is excluded from the utility, it is excluded from all Checks andno testing for violations will be performed on them.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.filefilters @@ -481,7 +487,7 @@ com.puppycrawl.tools.checkstyle.filters.SuppressionSingleFilterCheck: Package: com.puppycrawl.tools.checkstyle.filters com.puppycrawl.tools.checkstyle.filters.SuppressionXpathFilterCheck: Description: | -

Filter SuppressionXpathFilter works asSuppressionFilter.Additionally, filter processes suppress-xpath elements,which contains xpath-expressions. Xpath-expressionsare queries for suppressed nodes inside the AST tree.

Currently, filter does not support the following checks:

Also, the filter does not support suppressions inside javadoc reported by Javadoc checks:

Note, that support for these Checks will be available after resolving issues#5770 and#5777.

Currently, filter supports the followingxpath axes:

You can use the command line helper tool to generate xpathsuppressions based on your configuration file and input files.Seeherefor more details.

+

Filter SuppressionXpathFilter works asSuppressionFilter.Additionally, filter processes suppress-xpath elements,which contains xpath-expressions. Xpath-expressionsare queries for suppressed nodes inside the AST tree.

Currently, filter does not support the following checks:

Also, the filter does not support suppressions inside javadoc reported by Javadoc checks:

Note, that support for these Checks will be available after resolving issue#5770.

Currently, filter supports the followingxpath axes:

You can use the command line helper tool to generate xpathsuppressions based on your configuration file and input files.Seeherefor more details.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.filters @@ -493,7 +499,7 @@ com.puppycrawl.tools.checkstyle.filters.SuppressionXpathSingleFilterCheck: Package: com.puppycrawl.tools.checkstyle.filters com.puppycrawl.tools.checkstyle.filters.SuppressWarningsFilterCheck: Description: | -

Filter SuppressWarningsFilter uses annotation{@code SuppressWarnings} to suppress audit events.

Rationale: Same as forSuppressionCommentFilter. In the contrary to ithere, comments are not used comments but the builtin syntax of@SuppressWarnings. This can be perceived as amore elegant solution than using comments. Also this approachmaybe supported by various IDE.

Usage: This filter only works in conjunction with aSuppressWarningsHolder,since that check findsthe annotations in the Java files and makes them available forthe filter. Because of that, a configuration that includesthis filter must also includeSuppressWarningsHolder as a child module of theTreeWalker. Name of check in annotation is case-insensitiveand should be written with any dotted prefix or "Check" suffix removed.

+

Filter SuppressWarningsFilter uses annotation@SuppressWarnings to suppress audit events.

Rationale: Same as forSuppressionCommentFilter. In the contrary to ithere, comments are not used comments but the builtin syntax of@SuppressWarnings. This can be perceived as amore elegant solution than using comments. Also, this approachmaybe supported by various IDE.

Usage: This filter only works in conjunction with aSuppressWarningsHolder,since that check findsthe annotations in the Java files and makes them available forthe filter. Because of that, a configuration that includesthis filter must also includeSuppressWarningsHolder as a child module of theTreeWalker. Name of check in annotation is case-insensitiveand should be written with any dotted prefix or "Check" suffix removed.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.filters @@ -505,7 +511,7 @@ com.puppycrawl.tools.checkstyle.filters.SuppressWithNearbyCommentFilterCheck: Package: com.puppycrawl.tools.checkstyle.filters com.puppycrawl.tools.checkstyle.filters.SuppressWithPlainTextCommentFilterCheck: Description: | -

Filter SuppressWithPlainTextCommentFilter uses plain text to suppressaudit events. The filter can be used only to suppress audit events received fromthe checks which implement FileSetCheck interface. In other words, the checkswhich have Checker as a parent module. The filter knows nothing about AST,it treats only plain text comments and extracts the information requiredfor suppression from the plain text comments. Currently the filter supportsonly single line comments.

Please, be aware of the fact that, it is not recommended to use the filterfor Java code anymore, however you still are able to use it to suppress auditevents received from the checks which implement FileSetCheck interface.

Rationale: Sometimes there are legitimate reasons for violatinga check. When this is a matter of the code in question and notpersonal preference, the best place to override the policy is inthe code itself. Semi-structured comments can be associatedwith the check. This is sometimes superior to a separatesuppressions file, which must be kept up-to-date as the sourcefile is edited.

Note that the suppression comment should be put before the violation.You can use more than one suppression comment each on separate line.

+

Filter SuppressWithPlainTextCommentFilter uses plain text to suppressaudit events. The filter can be used only to suppress audit events received fromthe checks which implement FileSetCheck interface. In other words, the checkswhich have Checker as a parent module. The filter knows nothing about AST,it treats only plain text comments and extracts the information requiredfor suppression from the plain text comments. Currently, the filter supportsonly single-line comments.

Please, be aware of the fact that, it is not recommended to use the filterfor Java code anymore, however you still are able to use it to suppress auditevents received from the checks which implement FileSetCheck interface.

Rationale: Sometimes there are legitimate reasons for violatinga check. When this is a matter of the code in question and notpersonal preference, the best place to override the policy is inthe code itself. Semi-structured comments can be associatedwith the check. This is sometimes superior to a separatesuppressions file, which must be kept up-to-date as the sourcefile is edited.

Note that the suppression comment should be put before the violation.You can use more than one suppression comment each on separate line.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.filters @@ -517,7 +523,7 @@ com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck: Package: com.puppycrawl.tools.checkstyle.checks.header com.puppycrawl.tools.checkstyle.checks.header.RegexpHeaderCheck: Description: | -

Checks the header of a source file against a header that contains aregular expression for each line of the source header.

Rationale: In some projects checking against afixed header is not sufficient, e.g. the header might require acopyright line where the year information is not static.

For example, consider the following header:


line 1: ^/{71}$
line 2: ^// checkstyle:$
line 3: ^// Checks Java source code for adherence to a set of rules\.$
line 4: ^// Copyright \(C\) \d\d\d\d Oliver Burn$
line 5: ^// Last modification by \$Author.*\$$
line 6: ^/{71}$
line 7:
line 8: ^package
line 9:
line 10: ^import
line 11:
line 12: ^/\*\*
line 13: ^ \*([^/]|$)
line 14: ^ \*/

Lines 1 and 6 demonstrate a more compact notation for 71 '/'characters. Line 4 enforces that the copyright notice includes afour digit year. Line 5 is an example how to enforce revisioncontrol keywords in a file header. Lines 12-14 is a template forjavadoc (line 13 is so complicated to remove conflict with and ofjavadoc comment). Lines 7, 9 and 11 will be treated as '^$' andwill forcefully expect the line to be empty.

Different programming languages have different comment syntaxrules, but all of them start a comment with a non-wordcharacter. Hence you can often use the non-word characterclass to abstract away the concrete comment syntax and allowchecking the header for different languages with a singleheader definition. For example, consider the following headerspecification (note that this is not the full Apache licenseheader):


line 1: ^#!
line 2: ^<\?xml.*>$
line 3: ^\W*$
line 4: ^\W*Copyright 2006 The Apache Software Foundation or its licensors, as applicable\.$
line 5: ^\W*Licensed under the Apache License, Version 2\.0 \(the "License"\);$
line 6: ^\W*$

Lines 1 and 2 leave room for technical header lines, e.g. the"#!/bin/sh" line in Unix shell scripts, or the XML file headerof XML files. Set the multiline property to "1, 2" so theselines can be ignored for file types where they do no apply.Lines 3 through 6 define the actual header content. Note howlines 2, 4 and 5 use escapes for characters that have specialregexp semantics.

In default configuration, if header is not specified, the default valueof header is set to null and the check does not rise any violations.

+

Checks the header of a source file against a header that contains apattern for each line of the source header.

Rationale: In some projects checking against afixed header is not sufficient, e.g. the header might require acopyright line where the year information is not static.

For example, consider the following header:


line 1: ^/{71}$
line 2: ^// checkstyle:$
line 3: ^// Checks Java source code for adherence to a set of rules\.$
line 4: ^// Copyright \(C\) \d\d\d\d Oliver Burn$
line 5: ^// Last modification by \$Author.*\$$
line 6: ^/{71}$
line 7:
line 8: ^package
line 9:
line 10: ^import
line 11:
line 12: ^/\*\*
line 13: ^ \*([^/]|$)
line 14: ^ \*/

Lines 1 and 6 demonstrate a more compact notation for 71 '/'characters. Line 4 enforces that the copyright notice includes afour digit year. Line 5 is an example how to enforce revisioncontrol keywords in a file header. Lines 12-14 is a template forjavadoc (line 13 is so complicated to remove conflict with and ofjavadoc comment). Lines 7, 9 and 11 will be treated as '^$' andwill forcefully expect the line to be empty.

Different programming languages have different comment syntaxrules, but all of them start a comment with a non-wordcharacter. Hence, you can often use the non-word characterclass to abstract away the concrete comment syntax and allowchecking the header for different languages with a singleheader definition. For example, consider the following headerspecification (note that this is not the full Apache licenseheader):


line 1: ^#!
line 2: ^<\?xml.*>$
line 3: ^\W*$
line 4: ^\W*Copyright 2006 The Apache Software Foundation or its licensors, as applicable\.$
line 5: ^\W*Licensed under the Apache License, Version 2\.0 \(the "License"\);$
line 6: ^\W*$

Lines 1 and 2 leave room for technical header lines, e.g. the"#!/bin/sh" line in Unix shell scripts, or the XML file headerof XML files. Set the multiline property to "1, 2" so theselines can be ignored for file types where they do no apply.Lines 3 through 6 define the actual header content. Note howlines 2, 4 and 5 use escapes for characters that have specialregexp semantics.

In default configuration, if header is not specified, the default valueof header is set to null and the check does not rise any violations.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.header @@ -547,13 +553,13 @@ com.puppycrawl.tools.checkstyle.checks.imports.IllegalImportCheck: Package: com.puppycrawl.tools.checkstyle.checks.imports com.puppycrawl.tools.checkstyle.checks.imports.ImportControlCheck: Description: | -

Controls what can be imported in each package and file. Useful forensuring that application layering rules are not violated,especially on large projects.

You can control imports based on the a package name or based on the filename. When controlling packages, all files and sub-packages in the declaredpackage will be controlled by this check. To specify differences between a main packageand a sub-package, you must define the sub-package inside the main package. Whencontrolling file, only the file name is considered and only files processed byTreeWalker. The file's extension is ignored.

Short description of the behaviour:

The DTD for a import control XML document is at https://checkstyle.org/dtds/import_control_1_4.dtd. Itcontains documentation on each of the elements and attributes.

The check validates a XML document when it loads the document.To validate against the above DTD, include the followingdocument type declaration in your XML document:

<!DOCTYPE import-control PUBLIC"-//Checkstyle//DTD ImportControl Configuration 1.4//EN""https://checkstyle.org/dtds/import_control_1_4.dtd">

+

Controls what can be imported in each package and file. Useful forensuring that application layering rules are not violated,especially on large projects.

You can control imports based on the package name or based on the filename. When controlling packages, all files and sub-packages in the declaredpackage will be controlled by this check. To specify differences between a main packageand a sub-package, you must define the sub-package inside the main package. Whencontrolling file, only the file name is considered and only files processed byTreeWalker. The file's extension is ignored.

Short description of the behaviour:

The DTD for an import control XML document is at https://checkstyle.org/dtds/import_control_1_4.dtd. Itcontains documentation on each of the elements and attributes.

The check validates a XML document when it loads the document.To validate against the above DTD, include the followingdocument type declaration in your XML document:

<!DOCTYPE import-control PUBLIC"-//Checkstyle//DTD ImportControl Configuration 1.4//EN""https://checkstyle.org/dtds/import_control_1_4.dtd">

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.imports com.puppycrawl.tools.checkstyle.checks.imports.ImportOrderCheck: Description: | -

Checks the ordering/grouping of imports. Features are:

+

Checks the ordering/grouping of imports. Features are:

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.imports @@ -565,7 +571,7 @@ com.puppycrawl.tools.checkstyle.checks.imports.RedundantImportCheck: Package: com.puppycrawl.tools.checkstyle.checks.imports com.puppycrawl.tools.checkstyle.checks.imports.UnusedImportsCheck: Description: | -

Checks for unused import statements. Checkstyle uses a simple butvery reliable algorithm to report on unused import statements. Animport statement is considered unused if:

The main limitation of this check is handling the case wherean imported type has the same name as a declaration, such as amember variable.

For example, in the following case the import java.awt.Componentwill not be flagged as unused:


import java.awt.Component;
class FooBar {
private Object Component; // a bad practice in my opinion
...
}

+

Checks for unused import statements. Checkstyle uses a simple butvery reliable algorithm to report on unused import statements. Animport statement is considered unused if:

The main limitation of this check is handling the cases where:

For example, in the following case all imports will not be flagged as unused:


import java.awt.Component;
import static AstTreeStringPrinter.printFileAst;
import static DetailNodeTreeStringPrinter.printFileAst;
class FooBar {
private Object Component; // a bad practice in my opinion
void method() {
printFileAst(file); // two imports with the same name
}
}

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.imports @@ -595,7 +601,7 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocContentLocationCheck: Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck: Description: | -

Checks the Javadoc of a method or constructor. The scopeto verify is specified using the Scope class anddefaults to Scope.PRIVATE. To verify anotherscope, set property scope to a differentscope.

Violates parameters and type parametersfor which no param tags arepresent can be suppressed by defining propertyallowMissingParamTags.

Violates methods which return non-void but for which no return tag ispresent can be suppressed by defining propertyallowMissingReturnTag.

Violates exceptions which are declared to be thrown (by throws in the methodsignature or by throw new in the method body), but for which no throws tag ispresent by activation of property validateThrows.Note that throw new is not checked in the following places:

ATTENTION: Checkstyle does not have information about hierarchy of exception typesso usage of base class is considered as separate exception type.As workaround you need to specify both types in javadoc (parent and exact type).

Javadoc is not required on a method that is tagged with the@Override annotation. However underJava 5 it is not possible to mark a method required for aninterface (this was corrected under Java 6). HenceCheckstyle supports using the convention of using a single{@inheritDoc} tag instead of all theother tags.

Note that only inheritable items will allow the{@inheritDoc} tag to be used in placeof comments. Static methods at all visibilities, private non-staticmethods and constructors are not inheritable.

For example, if the following method isimplementing a method required by an interface, then theJavadoc could be done as:


/** {@inheritDoc} */
public int checkReturnTag(final int aTagIndex,
JavadocTag[] aTags,
int aLineNo)

+

Checks the Javadoc of a method or constructor.

Violates parameters and type parametersfor which no param tags arepresent can be suppressed by defining propertyallowMissingParamTags.

Violates methods which return non-void but for which no return tag ispresent can be suppressed by defining propertyallowMissingReturnTag.

Violates exceptions which are declared to be thrown (by throws in the methodsignature or by throw new in the method body), but for which no throws tag ispresent by activation of property validateThrows.Note that throw new is not checked in the following places:

ATTENTION: Checkstyle does not have information about hierarchy of exception typesso usage of base class is considered as separate exception type.As workaround, you need to specify both types in javadoc (parent and exact type).

Javadoc is not required on a method that is tagged with the@Override annotation. However, underJava 5 it is not possible to mark a method required for aninterface (this was corrected under Java 6). Hence,Checkstyle supports using the convention of using a single{@inheritDoc} tag instead of all theother tags.

Note that only inheritable items will allow the{@inheritDoc} tag to be used in placeof comments. Static methods at all visibilities, private non-staticmethods and constructors are not inheritable.

For example, if the following method isimplementing a method required by an interface, then theJavadoc could be done as:


/** {@inheritDoc} */
public int checkReturnTag(final int aTagIndex,
JavadocTag[] aTags,
int aLineNo)

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.javadoc @@ -613,7 +619,7 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMissingWhitespaceAfterAste Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocPackageCheck: Description: | -

Checks that each Java package has a Javadoc file used forcommenting. By default it only allows a package-info.java file, but can beconfigured to allow a package.htmlfile.

A violation will be reported if both files exist as this is notallowed by the Javadoc tool.

+

Checks that each Java package has a Javadoc file used forcommenting. By default, it only allows a package-info.java file, but can beconfigured to allow a package.htmlfile.

A violation will be reported if both files exist as this is notallowed by the Javadoc tool.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.javadoc @@ -625,7 +631,7 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocParagraphCheck: Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocStyleCheck: Description: | -

Validates Javadoc comments to help ensure they are well formed.

The following checks are performed:

These checks were patterned after the checks made by the DocCheckdoclet available from Sun. Note: Original Sun's DocCheck tool does not exist anymore.

+

Validates Javadoc comments to help ensure they are well formed.

The following checks are performed:

These checks were patterned after the checks made by the DocCheckdoclet available from Sun. Note: Original Sun's DocCheck tool does not exist anymore.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.javadoc @@ -637,7 +643,7 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTagContinuationIndentation Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTypeCheck: Description: | -

Checks the Javadoc comments for type definitions.By default, does not check for author or version tags. Thescope to verify is specified using the Scopeclass and defaults to Scope.PRIVATE. To verifyanother scope, set property scope to one of theScope constants. To define the format for anauthor tag or a version tag, set property authorFormat orversionFormat respectively to aregular expression.

Does not perform checks for author and version tags for innerclasses, as they should be redundant because of outer class.

Error messages about type parameters and record components for which noparam tags are present can be suppressed by defining propertyallowMissingParamTags.

+

Checks the Javadoc comments for type definitions.By default, does not check for author or version tags. Thescope to verify is specified using the Scopeclass and defaults to Scope.PRIVATE. To verifyanother scope, set property scope to one of theScope constants. To define the format for anauthor tag or a version tag, set property authorFormat orversionFormat respectively to apattern.

Does not perform checks for author and version tags for innerclasses, as they should be redundant because of outer class.

Error messages about type parameters and record components for which noparam tags are present can be suppressed by defining propertyallowMissingParamTags.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.javadoc @@ -649,13 +655,13 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocVariableCheck: Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.MissingJavadocMethodCheck: Description: | -

Checks for missing Javadoc comments for a method or constructor.The scope to verify is specified using the Scope class anddefaults to Scope.PUBLIC. To verify anotherscope, set property scope to a differentscope.

Javadoc is not required on a method that is tagged with the@Override annotation. However underJava 5 it is not possible to mark a method required for aninterface (this was corrected under Java 6). HenceCheckstyle supports using the convention of using a single{@inheritDoc} tag instead of all theother tags.

For getters and setters for the property allowMissingPropertyJavadoc,the methods must match exactly the structures below.

public void setNumber(final int number){mNumber = number;}public int getNumber(){return mNumber;}public boolean isSomething(){return false;}

+

Checks for missing Javadoc comments for a method or constructor.The scope to verify is specified using the Scope class anddefaults to Scope.PUBLIC. To verify anotherscope, set property scope to a differentscope.

Javadoc is not required on a method that is tagged with the@Override annotation. However, underJava 5 it is not possible to mark a method required for aninterface (this was corrected under Java 6). Hence,Checkstyle supports using the convention of using a single{@inheritDoc} tag instead of all theother tags.

For getters and setters for the property allowMissingPropertyJavadoc,the methods must match exactly the structures below.


public void setNumber(final int number)
{
mNumber = number;
}

public int getNumber()
{
return mNumber;
}

public boolean isSomething()
{
return false;
}

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.MissingJavadocPackageCheck: Description: | -

Checks for missing Javadoc comments in package-info.java files.

Rationale: description and other related documentation for a package can be written upin the package-info.java file and it gets used in the production of the Javadocs.See link for more info.

+

Checks for missing package definition Javadoc comments in package-info.java files.

Rationale: description and other related documentation for a package can be written upin the package-info.java file and it gets used in the production of the Javadocs.See link for more info.

This check specifically only validates package definitions. It will not validate anymethods or interfaces declared in the package-info.java file.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.javadoc @@ -679,13 +685,13 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.RequireEmptyLineBeforeBlockTagGro Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.SingleLineJavadocCheck: Description: | -

Checks that a Javadoc block can fit in a single line and doesn'tcontain block tags. Javadoc comment that contains at least one block tagshould be formatted in a few lines.

+

Checks that a Javadoc block can fit in a single-line and doesn'tcontain block tags. Javadoc comment that contains at least one block tagshould be formatted in a few lines.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.SummaryJavadocCheck: Description: | -

Checks thatJavadoc summary sentence does not contain phrases that are not recommended to use.Summaries that contain only the {@inheritDoc} tag are skipped. Check alsoviolate Javadoc that does not contain first sentence.

+

Checks thatJavadoc summary sentence does not contain phrases that are not recommended to use.Summaries that contain only the {@inheritDoc} tag are skipped. Summariesthat contain a non-empty {@code {@return}} are allowed. Check also violate Javadoc thatdoes not contain first sentence, though with {@code {@return}} a period is not requiredas the Javadoc tool adds it.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.javadoc @@ -697,25 +703,25 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.WriteTagCheck: Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.metrics.BooleanExpressionComplexityCheck: Description: | -

Restricts the number of boolean operators (&&, ||,&, | and ^) in an expression.

Rationale: Too many conditions leads to code that is difficultto read and hence debug and maintain.

Note that the operators & and| are not only integer bitwise operators, they are also thenon-shortcut versions of the boolean operators&& and ||.

Note that &, | and ^ are not checkedif they are part of constructor or method callbecause they can be applied to non boolean variables andCheckstyle does not know types of methods from different classes.

+

Restricts the number of boolean operators (&&, ||,&, | and ^) in an expression.

Rationale: Too many conditions leads to code that is difficultto read and hence debug and maintain.

Note that the operators & and| are not only integer bitwise operators, they are also thenon-shortcut versions of the boolean operators&& and ||.

Note that &, | and ^ are not checkedif they are part of constructor or method callbecause they can be applied to non-boolean variables andCheckstyle does not know types of methods from different classes.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.metrics com.puppycrawl.tools.checkstyle.checks.metrics.ClassDataAbstractionCouplingCheck: Description: | -

Measures the number of instantiations of otherclasses within the given class or record. This type of coupling is notcaused by inheritance or the object orientedparadigm. Generally speaking, any data type with other datatypes 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:

  1. Iterates over the list of tokens (defined below) and counts all mentioned classes.
  2. If a class was imported with direct import (i.e.import java.math.BigDecimal), or the class was referenced with thepackage name (i.e. java.math.BigDecimal value) and the package wasadded to the excludedPackages parameter, the class does notincrease complexity.
  3. If a class name was added to the excludedClasses parameter,the class does not increase complexity.

+

Measures the number of instantiations of otherclasses within the given class or record. This type of coupling is notcaused by inheritance or the object-orientedparadigm. Generally speaking, any data type with other datatypes 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:

  1. Iterates over the list of tokens (defined below) and counts all mentioned classes.
  2. If a class was imported with direct import (i.e.import java.math.BigDecimal), or the class was referenced with thepackage name (i.e. java.math.BigDecimal value) and the package wasadded to the excludedPackages parameter, the class does notincrease complexity.
  3. If a class name was added to the excludedClasses parameter,the class does not increase complexity.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.metrics com.puppycrawl.tools.checkstyle.checks.metrics.ClassFanOutComplexityCheck: Description: | -

Checks the number of other types a given class/record/interface/enum/annotationrelies on. Also the square of this has been shown to indicate the amount ofmaintenance required in functional programs (on a file basis) at least.

This check processes files in the following way:

  1. Iterates over all tokens that might contain type reference.
  2. If a class was imported with direct import (i.e.import java.math.BigDecimal), or the class was referenced with thepackage name (i.e. java.math.BigDecimal value) and the package wasadded to the excludedPackages parameter, the class does not increasecomplexity.
  3. If a class name was added to the excludedClasses parameter,the class does not increase complexity.

+

Checks the number of other types a given class/record/interface/enum/annotationrelies on. Also, the square of this has been shown to indicate the amount ofmaintenance required in functional programs (on a file basis) at least.

This check processes files in the following way:

  1. Iterates over all tokens that might contain type reference.
  2. If a class was imported with direct import (i.e.import java.math.BigDecimal), or the class was referenced with thepackage name (i.e. java.math.BigDecimal value) and the package wasadded to the excludedPackages parameter, the class does not increasecomplexity.
  3. If a class name was added to the excludedClasses parameter,the class does not increase complexity.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.metrics com.puppycrawl.tools.checkstyle.checks.metrics.CyclomaticComplexityCheck: Description: | -

Checks cyclomatic complexity against a specified limit.It is a measure of the minimum number ofpossible paths through the source and therefore the number ofrequired 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, casestatements and operators && and ||in the body of target.

By pure theory level 1-4 is considered easy to test, 5-7 OK, 8-10consider re-factoring to ease testing, and 11+ re-factor now as testing will be painful.

When it comes to code quality measurement by this metriclevel 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 fewmethods without damaging readability of code or encapsulation.

+

Checks cyclomatic complexity against a specified limit.It is a measure of the minimum number ofpossible paths through the source and therefore the number ofrequired tests, it is not 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, casestatements and operators && and ||in the body of target.

By pure theory level 1-4 is considered easy to test, 5-7 OK, 8-10consider re-factoring to ease testing, and 11+ re-factor now as testing will be painful.

When it comes to code quality measurement by this metriclevel 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 fewmethods without damaging readability of code or encapsulation.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.metrics @@ -727,13 +733,13 @@ com.puppycrawl.tools.checkstyle.checks.metrics.JavaNCSSCheck: Package: com.puppycrawl.tools.checkstyle.checks.metrics com.puppycrawl.tools.checkstyle.checks.metrics.NPathComplexityCheck: Description: | -

Checks the NPATH complexity against a specified limit.

The NPATH metric computes the number of possible executionpaths through a function(method). It takes into account the nesting ofconditional 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 toavoid problem of Cyclomatic complexity metric like nesting level within afunction(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 establishedfor a function. The value 200 is based on studies doneat AT&T Bell Laboratories [1988 year].
Some of the most effective methods of reducing the NPATH value include:
Although strategies to reduce the NPATH complexityof functions are important, care must be taken not todistort the logical clarity of the software by applying astrategy to reduce the complexity of functions. That is,there is a point of diminishing return beyond which afurther attempt at reduction of complexity distorts thelogical clarity of the system structure.
Examples
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 label1
break1
ExpressionsNumber of && and || operators in expression. Nooperators - 0
continue1
return1
Statement (even sequential statements)1
Empty block {}1
Function call1
Function(Method) declaration or BlockP(i=1:i=N)NP(Statement[i])

Rationale: Nejmeh says that his group had an informal NPATHlimit of 200 on individual routines; functions(methods) that exceededthis value were candidates for further decomposition - or atleast a closer look.Please do not be fanatic with limit 200- choose number that suites your project style. Limit 200 isempirical number base on some sources of at AT&T Bell Laboratoriesof 1988 year.

+

Checks the NPATH complexity against a specified limit.

The NPATH metric computes the number of possible executionpaths through a function(method). It takes into account the nesting ofconditional statements and multipart boolean expressions(A && B, C || D, E ? F :G and their combinations).

The NPATH metric was designed base on Cyclomatic complexity toavoid problem of Cyclomatic complexity metric like nesting level within afunction(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 establishedfor a function. The value 200 is based on studies doneat AT&T Bell Laboratories [1988 year].
Some of the most effective methods of reducing the NPATH value include:
Although strategies to reduce the NPATH complexityof functions are important, care must be taken not todistort the logical clarity of the software by applying astrategy to reduce the complexity of functions. That is,there is a point of diminishing return beyond which afurther attempt at reduction of complexity distorts thelogical clarity of the system structure.
Examples
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 label1
break1
ExpressionsNumber of && and || operators in expression. Nooperators - 0
continue1
return1
Statement (even sequential statements)1
Empty block {}1
Function call1
Function(Method) declaration or BlockP(i=1:i=N)NP(Statement[i])

Rationale: Nejmeh says that his group had an informal NPATHlimit of 200 on individual routines; functions(methods) that exceededthis value were candidates for further decomposition - or atleast a closer look.Please do not be fanatic with limit 200- choose number that suites your project style. Limit 200 isempirical number base on some sources of at AT&T Bell Laboratoriesof 1988 year.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.metrics com.puppycrawl.tools.checkstyle.checks.ArrayTypeStyleCheck: Description: | -

Checks the style of array type definitions. Some like Java style:public static void main(String[] args) and some likeC style: public static void main(String args[]).

By default the Check enforces Java style.

This check strictly enforces only Java style for method return typesregardless of the value for 'javaStyle'. For example, byte[] getData().This is because C doesn't compile methods with array declarations on the name.

+

Checks the style of array type definitions. Some like Java style:public static void main(String[] args) and some likeC style: public static void main(String args[]).

By default, the Check enforces Java style.

This check strictly enforces only Java style for method return typesregardless of the value for 'javaStyle'. For example, byte[] getData().This is because C doesn't compile methods with array declarations on the name.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks @@ -745,13 +751,13 @@ com.puppycrawl.tools.checkstyle.checks.AvoidEscapedUnicodeCharactersCheck: Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.indentation.CommentsIndentationCheck: Description: | -

Controls the indentation between comments and surrounding code.Comments are indented at the same level as the surrounding code.Detailed info about such convention can be foundhere

Please take a look at the following examples to understand how the check works:

Example #1: Block comments.


1 /*
2 * it is Ok
3 */
4 boolean bool = true;
5
6 /* violation
7 * (block comment should have the same indentation level as line 9)
8 */
9 double d = 3.14;

Example #2: Comment is placed at the end of the block and has previous statement.


1 public void foo1() {
2 foo2();
3 // it is OK
4 }
5
6 public void foo2() {
7 foo3();
8 // violation (comment should have the same indentation level as line 7)
9 }

Example #3: Comment is used as a single line border to separate groups of methods.


1 /////////////////////////////// it is OK
2
3 public void foo7() {
4 int a = 0;
5 }
6
7 ///////////////////////////// violation (should have the same indentation level as line 9)
8
9 public void foo8() {}

Example #4: Comment has distributed previous statement.


1 public void foo11() {
2 CheckUtil
3 .getFirstNode(new DetailAST())
4 .getFirstChild()
5 .getNextSibling();
6 // it is OK
7 }
8
9 public void foo12() {
10 CheckUtil
11 .getFirstNode(new DetailAST())
12 .getFirstChild()
13 .getNextSibling();
14 // violation (should have the same indentation level as line 10)
15 }

Example #5: Single line block comment is placed within an empty code block.Note, if comment is placed at the end of the empty code block, we have Checkstyle'slimitations to clearly detect user intention of explanation target - above or below. Theonly case we can assume as a violation is when a single line comment within the emptycode block has indentation level that is lower than the indentation level of the closingright curly brace.


1 public void foo46() {
2 // comment
3 // block
4 // it is OK (we cannot clearly detect user intention of explanation target)
5 }
6
7 public void foo46() {
8 // comment
9 // block
10 // violation (comment should have the same indentation level as line 11)
11 }

Example #6: 'fallthrough' comments and similar.


0 switch(a) {
1 case "1":
2 int k = 7;
3 // it is OK
4 case "2":
5 int k = 7;
6 // it is OK
7 case "3":
8 if (true) {}
9 // violation (should have the same indentation level as line 8 or 10)
10 case "4":
11 case "5": {
12 int a;
13 }
14 // fall through (it is OK)
15 case "12": {
16 int a;
17 }
18 default:
19 // it is OK
20 }

Example #7: Comment is placed within a distributed statement.


1 String breaks = "J"
2 // violation (comment should have the same indentation level as line 3)
3 + "A"
4 // it is OK
5 + "V"
6 + "A"
7 // it is OK
8 ;

Example #8: Comment is placed within an empty case block.Note, if comment is placed at the end of the empty case block, we have Checkstyle'slimitations to clearly detect user intention of explanation target - above or below. Theonly case we can assume as a violation is when a single line comment within the empty caseblock has indentation level that is lower than the indentation level of the next casetoken.


1 case 4:
2 // it is OK
3 case 5:
4 // violation (should have the same indentation level as line 3 or 5)
5 case 6:

Example #9: Single line block comment has previous and next statement.


1 String s1 = "Clean code!";
2 s.toString().toString().toString();
3 // single line
4 // block
5 // comment (it is OK)
6 int a = 5;
7
8 String s2 = "Code complete!";
9 s.toString().toString().toString();
10 // violation (should have the same indentation level as line 11)
11 // violation (should have the same indentation level as line 12)
12 // violation (should have the same indentation level as line 13)
13 int b = 18;

Example #10: Comment within the block tries to describe the next code block.


1 public void foo42() {
2 int a = 5;
3 if (a == 5) {
4 int b;
5 // it is OK
6 } else if (a ==6) { ... }
7 }
8
9 public void foo43() {
10 try {
11 int a;
12 // Why do we catch exception here? - violation (not the same indentation as line 11)
13 } catch (Exception e) { ... }
14 }

+

Controls the indentation between comments and surrounding code.Comments are indented at the same level as the surrounding code.Detailed info about such convention can be foundhere

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.indentation com.puppycrawl.tools.checkstyle.checks.DescendantTokenCheck: Description: | -

Checks for restricted tokens beneath other tokens.

WARNING: This is a very powerful and flexible check, but, at thesame time, it is low-level and very implementation-dependent becauseits results depend on the grammar we use to build abstract syntaxtrees. Thus we recommend using other checks when they provide thedesired functionality. Essentially, this check just works on the levelof an abstract syntax tree and knows nothing about language structures.

+

Checks for restricted tokens beneath other tokens.

WARNING: This is a very powerful and flexible check, but, at thesame time, it is low-level and very implementation-dependent becauseits results depend on the grammar we use to build abstract syntaxtrees. Thus, we recommend using other checks when they provide thedesired functionality. Essentially, this check just works on the levelof an abstract syntax tree and knows nothing about language structures.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks @@ -769,19 +775,19 @@ com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck: Package: com.puppycrawl.tools.checkstyle.checks.indentation com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheck: Description: | -

Checks whether files end with a line separator.

Rationale: Any source files and text files in general shouldend with a line separator to let other easily add new contentat the end of file and "diff" command does not show previous lines as changed.

Example (line 36 should not be in diff):


@@ -32,4 +32,5 @@ ForbidWildcardAsReturnTypeCheck.returnTypeClassNamesIgnoreRegex
PublicReferenceToPrivateTypeCheck.name = Public Reference To Private Type

StaticMethodCandidateCheck.name = Static Method Candidate
-StaticMethodCandidateCheck.desc = Checks whether private methods should be declared as static.
\ No newline at end of file
+StaticMethodCandidateCheck.desc = Checks whether private methods should be declared as static.
+StaticMethodCandidateCheck.skippedMethods = Method names to skip during the check.

It can also trick the VCS to report the wrong owner for such lines.An engineer who has added nothing but a newline character becomesthe last known author for the entire line. As a result, a mate can askhim a question to which he will not give the correct answer.

Old Rationale: CVS source control managementsystems will even print a warning when itencounters a file that doesn't end with a line separator.

Attention: property fileExtensions works with files that are passed by similar propertyfor at Checker.Please make sure required file extensions are mentioned at Checker's fileExtensionsproperty.

+

Checks whether files end with a line separator.

Rationale: Any source files and text files in general shouldend with a line separator to let other easily add new contentat the end of file and "diff" command does not show previous lines as changed.

Example (the line with 'No newline at end of file' should not be in the diff):


@@ -32,4 +32,5 @@ ForbidWildcardAsReturnTypeCheck.returnTypeClassNamesIgnoreRegex
PublicReferenceToPrivateTypeCheck.name = Public Reference To Private Type

StaticMethodCandidateCheck.name = Static Method Candidate
-StaticMethodCandidateCheck.desc = Checks whether private methods should be declared as static.
\ No newline at end of file
+StaticMethodCandidateCheck.desc = Checks whether private methods should be declared as static.
+StaticMethodCandidateCheck.skippedMethods = Method names to skip during the check.

It can also trick the VCS to report the wrong owner for such lines.An engineer who has added nothing but a newline character becomesthe last known author for the entire line. As a result, a mate can askhim a question to which he will not give the correct answer.

Old Rationale: CVS source control managementsystems will even print a warning when itencounters a file that doesn't end with a line separator.

Attention: property fileExtensions works with files that are passed by similar propertyfor at Checker.Please make sure required file extensions are mentioned at Checker's fileExtensionsproperty.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.NoCodeInFileCheck: Description: | -

Checks whether file contains code.Files which are considered to have no code:

+

Checks whether file contains code.Files which are considered to have no code:

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.OrderedPropertiesCheck: Description: | -

Detects if keys in properties files are in correct order.

Rationale: Sorted properties make it easy for people to find required properties by namein file. It makes merges more easy. While there are no problems at runtime.This check is valuable only on files with string resources where order of linesdoes not matter at all, but this can be improved.E.g.: checkstyle/src/main/resources/com/puppycrawl/tools/checkstyle/messages.propertiesYou may suppress warnings of this check for files that have an logical structure likebuild files or log4j configuration files. See SuppressionFilter.<suppress checks="OrderedProperties"files="log4j.properties|ResourceBundle/Bug.*.properties|logging.properties"/>

Known limitation: The key should not contain a newline.The string compare will work, but not the line number reporting.

+

Detects if keys in properties files are in correct order.

Rationale: Sorted properties make it easy for people to find required properties by namein file. This makes it easier to merge. While there are no problems at runtime.This check is valuable only on files with string resources where order of linesdoes not matter at all, but this can be improved.E.g.: checkstyle/src/main/resources/com/puppycrawl/tools/checkstyle/messages.propertiesYou may suppress warnings of this check for files that have a logical structure likebuild files or log4j configuration files. See SuppressionFilter.<suppress checks="OrderedProperties"files="log4j.properties|ResourceBundle/Bug.*.properties|logging.properties"/>

Known limitation: The key should not contain a newline.The string compare will work, but not the line number reporting.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks @@ -793,13 +799,13 @@ com.puppycrawl.tools.checkstyle.checks.OuterTypeFilenameCheck: Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.TodoCommentCheck: Description: | -

Checks for TODO: comments. Actuallyit is a genericregularexpression matcher on Java comments. To check for otherpatterns in Java comments, set the format property.

+

Checks for TODO: comments. Actuallyit is a genericpattern matcher on Java comments. To check for otherpatterns in Java comments, set the format property.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.TrailingCommentCheck: Description: | -

The check to ensure that requires that comments be the only thing ona line. For the case of // comments that means that the only thingthat should precede it is whitespace. It doesn't check comments ifthey do not end a line; for example, it accepts the following:Thread.sleep( 10 /*some comment here*/ ); Formatproperty is intended to deal with the } // while example.

Rationale: Steve McConnell in Code Complete suggests thatendline comments are a bad practice. An end line comment would beone that is on the same line as actual code. For example:


a = b + c; // Some insightful comment
d = e / f; // Another comment for this line

Quoting Code Complete for the justification:

McConnell's comments on being hard to maintain when the size of the linechanges are even more important in the age of automatedrefactorings.

+

The check to ensure that lines with code do not end with comment.For the case of // comments that means that the only thingthat should precede it is whitespace. It doesn't check comments ifthey do not end a line; for example, it accepts the following:Thread.sleep( 10 /*some comment here*/ ); Formatproperty is intended to deal with the } // while example.

Rationale: Steve McConnell in Code Complete suggests thatendline comments are a bad practice. An end line comment would beone that is on the same line as actual code. For example:


a = b + c; // Some insightful comment
d = e / f; // Another comment for this line

Quoting Code Complete for the justification:

McConnell's comments on being hard to maintain when the size of the linechanges are even more important in the age of automatedrefactorings.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks @@ -811,7 +817,7 @@ com.puppycrawl.tools.checkstyle.checks.TranslationCheck: Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.UncommentedMainCheck: Description: | -

Detects uncommented main methods.

Rationale: A main method is often used for debuggingpurposes. When debugging is finished, developers often forgetto remove the method, which changes the API and increases thesize of the resulting class or JAR file. With the exception ofthe real program entry points, all main methods should beremoved or commented out of the sources.

+

Detects uncommented main methods.

Rationale: A main method is often used for debuggingpurposes. When debugging is finished, developers often forgetto remove the method, which changes the API and increases thesize of the resulting class or JAR file. Except forthe real program entry points, all main methods should beremoved or commented out of the sources.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks @@ -841,26 +847,26 @@ com.puppycrawl.tools.checkstyle.checks.modifier.InterfaceMemberImpliedModifierCh Package: com.puppycrawl.tools.checkstyle.checks.modifier com.puppycrawl.tools.checkstyle.checks.modifier.ModifierOrderCheck: Description: | -

Checks that the order of modifiers conforms to the suggestions inthe JavaLanguage specification, § 8.1.1, 8.3.1, 8.4.3 and9.4. The correct order is:

  1. public
  2. protected
  3. private
  4. abstract
  5. default
  6. static
  7. final
  8. transient
  9. volatile
  10. synchronized
  11. native
  12. strictfp

In additional, modifiers are checked to ensure all annotations aredeclared before all other modifiers.

Rationale: Code is easier to read if everybody follows a standard.

ATTENTION: We skiptype annotations from validation.

+

Checks that the order of modifiers conforms to the suggestions inthe JavaLanguage specification, § 8.1.1, 8.3.1, 8.4.3 and9.4. The correct order is:

  1. public
  2. protected
  3. private
  4. abstract
  5. default
  6. static
  7. sealed
  8. non-sealed
  9. final
  10. transient
  11. volatile
  12. synchronized
  13. native
  14. strictfp

In additional, modifiers are checked to ensure all annotations aredeclared before all other modifiers.

Rationale: Code is easier to read if everybody follows a standard.

ATTENTION: We skiptype annotations from validation.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.modifier com.puppycrawl.tools.checkstyle.checks.modifier.RedundantModifierCheck: Description: | -

Checks for redundant modifiers.

Rationale: The Java Language Specification stronglydiscourages the usage of public and abstract for methoddeclarations in interface definitions as a matter of style.

The check validates:

  1. Interface and annotation definitions.
  2. Final modifier on methods of final and anonymous classes.
  3. Inner interface declarations that are declaredas static.
  4. Class constructors.
  5. Nested enum definitions that are declaredas static.

Interfaces by definition are abstract so the abstractmodifier on the interface is redundant.

Classes inside of interfaces by definition are public and static,so the public and static modifierson the inner classes are redundant. On the other hand, classesinside of interfaces can be abstract or non abstract.So, abstract modifier is allowed.

Fields in interfaces and annotations are automaticallypublic, static and final, so these modifiers are redundant aswell.

As annotations are a form of interface, their fields are alsoautomatically public, static and final just as theirannotation fields are automatically public and abstract.

Enums by definition are static implicit subclasses of java.lang.Enum<E>.So, the static modifier on the enums is redundant. In addition,if enum is inside of interface, public modifier is also redundant.

Enums can also contain abstract methods and methods which can be overridden by thedeclared enumeration fields.See the following example:


public enum EnumClass {
FIELD_1,
FIELD_2 {
@Override
public final void method1() {} // violation expected
};

public void method1() {}
public final void method2() {} // no violation expected
}

Since these methods can be overridden in these situations, the final methods are notmarked as redundant even though they can't be extended by other classes/enums.

Nested enum types are always static by default.

Final classes by definition cannot be extended so the finalmodifier on the method of a final class is redundant.

Public modifier for constructors in non-public non-protected classesis always obsolete:


public class PublicClass {
public PublicClass() {} // OK
}

class PackagePrivateClass {
public PackagePrivateClass() {} // violation expected
}

There is no violation in the following example,because removing public modifier from ProtectedInnerClassconstructor will make this code not compiling:


package a;
public class ClassExample {
protected class ProtectedInnerClass {
public ProtectedInnerClass () {}
}
}

package b;
import a.ClassExample;
public class ClassExtending extends ClassExample {
ProtectedInnerClass pc = new ProtectedInnerClass();
}

+

Checks for redundant modifiers.

Rationale: The Java Language Specification stronglydiscourages the usage of public and abstract for methoddeclarations in interface definitions as a matter of style.

The check validates:

  1. Interface and annotation definitions.
  2. Final modifier on methods of final and anonymous classes.
  3. Type declarations nested under interfaces that are declared as publicor static.
  4. Class constructors.
  5. Nested enum definitions that are declaredas static.
  6. record definitions that are declared as final and nestedrecord definitions that are declared as static.

interfaces by definition are abstract so the abstract modifier isredundant on them.

Type declarations nested under interfaces by definition are public and static,so the public and static modifiers on nested typedeclarations are redundant. On the other hand, classes inside of interfaces canbe abstract or non abstract. So, abstract modifier is allowed.

Fields in interfaces and annotations are automaticallypublic, static and final, so these modifiers are redundant aswell.

As annotations are a form of interface, their fields are alsoautomatically public, static and final just as theirannotation fields are automatically public and abstract.

A record class is implicitly final and cannot be abstract, these restrictions emphasizethat the API of a record class is defined solely by its state description, and cannot beenhanced later by another class. Nested records are implicitly static. This avoids animmediately enclosing instance which would silently add state to the record class.See JEP 395 for more info.

Enums by definition are static implicit subclasses of java.lang.Enum<E>.So, the static modifier on the enums is redundant. In addition,if enum is inside of interface, public modifier is also redundant.

Enums can also contain abstract methods and methods which can be overridden by thedeclared enumeration fields.See the following example:


public enum EnumClass {
FIELD_1,
FIELD_2 {
@Override
public final void method1() {} // violation expected
};

public void method1() {}
public final void method2() {} // no violation expected
}

Since these methods can be overridden in these situations, the final methods are notmarked as redundant even though they can't be extended by other classes/enums.

Nested enum types are always static by default.

Final classes by definition cannot be extended so the finalmodifier on the method of a final class is redundant.

Public modifier for constructors in non-public non-protected classesis always obsolete:


public class PublicClass {
public PublicClass() {} // OK
}

class PackagePrivateClass {
public PackagePrivateClass() {} // violation expected
}

There is no violation in the following example,because removing public modifier from ProtectedInnerClassconstructor will make this code not compiling:


package a;
public class ClassExample {
protected class ProtectedInnerClass {
public ProtectedInnerClass () {}
}
}

package b;
import a.ClassExample;
public class ClassExtending extends ClassExample {
ProtectedInnerClass pc = new ProtectedInnerClass();
}

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.modifier ".OverviewCheck": {} com.puppycrawl.tools.checkstyle.checks.naming.AbbreviationAsWordInNameCheck: Description: | -

Validates abbreviations (consecutive capital letters) length in identifier name,it also allows to enforce camel case naming. Please read more atGoogle Style Guideto get to know how to avoid long abbreviations in names.

allowedAbbreviationLength specifies how many consecutive capital letters areallowed in the identifier.A value of 3 indicates that up to 4 consecutive capital letters are allowed,one after the other, before a violation is printed. The identifier 'MyTEST' would beallowed, but 'MyTESTS' would not be.A value of 0 indicates that only 1 consecutive capital letter is allowed. Thisis what should be used to enforce strict camel casing. The identifier 'MyTest' wouldbe allowed, but 'MyTEst' would not be.

ignoreFinal, ignoreStatic, and ignoreStaticFinalcontrol whether variables with the respective modifiers are to be ignored.Note that a variable that is both static and final will always be considered underignoreStaticFinal only, regardless of the values of ignoreFinaland ignoreStatic. So for example if ignoreStatic is true butignoreStaticFinal is false, then static final variables will not be ignored.

+

Validates abbreviations (consecutive capital letters) length in identifier name,it also allows to enforce camel case naming. Please read more atGoogle Style Guideto get to know how to avoid long abbreviations in names.

'_' is considered as word separator in identifier name.

allowedAbbreviationLength specifies how many consecutive capital letters areallowed in the identifier.A value of 3 indicates that up to 4 consecutive capital letters are allowed,one after the other, before a violation is printed. The identifier 'MyTEST' would beallowed, but 'MyTESTS' would not be.A value of 0 indicates that only 1 consecutive capital letter is allowed. Thisis what should be used to enforce strict camel casing. The identifier 'MyTest' wouldbe allowed, but 'MyTEst' would not be.

ignoreFinal, ignoreStatic, and ignoreStaticFinalcontrol whether variables with the respective modifiers are to be ignored.Note that a variable that is both static and final will always be considered underignoreStaticFinal only, regardless of the values of ignoreFinaland ignoreStatic. So for example if ignoreStatic is true butignoreStaticFinal is false, then static final variables will not be ignored.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.naming com.puppycrawl.tools.checkstyle.checks.naming.AbstractClassNameCheck: Description: | -

Ensures that the names of abstract classes conforming to some regular expression andcheck that abstract modifier exists.

Rationale: Abstract classes are convenience base class implementations ofinterfaces, not types as such. As such they should be named to indicate this.Also if names of classes starts with 'Abstract' it's very convenient thatthey will have abstract modifier.

+

Ensures that the names of abstract classes conforming to some pattern andcheck that abstract modifier exists.

Rationale: Abstract classes are convenience base class implementations ofinterfaces, not types as such. As such they should be named to indicate this.Also, if names of classes starts with 'Abstract' it's very convenient thatthey will have abstract modifier.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.naming @@ -884,7 +890,7 @@ com.puppycrawl.tools.checkstyle.checks.naming.ConstantNameCheck: Package: com.puppycrawl.tools.checkstyle.checks.naming "

com.puppycrawl.tools.checkstyle.checks.naming

.IllegalIdentifierNameCheck": Description: | -

Checks identifiers with a regular expression for a set of illegal names, such as thosethat are restricted or contextual keywords. Examples include "yield", "record","_", and "var". Please read more atJava Language Specificationto get to know more about restricted keywords. Since this check uses aregular expression to specify valid identifiers, users can also prohibit the usageof certain symbols, such as "$", or any non-ascii character.

+

Checks identifiers with a pattern for a set of illegal names, such as thosethat are restricted or contextual keywords. Examples include "yield", "record","_", and "var". Please read more atJava Language Specificationto get to know more about restricted keywords. Since this check uses apattern to specify valid identifiers, users can also prohibit the usageof certain symbols, such as "$", or any non-ascii character.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: "

com.puppycrawl.tools.checkstyle.checks.naming

" @@ -932,7 +938,7 @@ com.puppycrawl.tools.checkstyle.checks.naming.MethodTypeParameterNameCheck: Package: com.puppycrawl.tools.checkstyle.checks.naming com.puppycrawl.tools.checkstyle.checks.naming.PackageNameCheck: Description: | -

Checks that package names conform to a specified pattern.

The default value of format for module PackageName has beenchosen to match the requirements in the JavaLanguage specification and the Sun coding conventions. Howeverboth underscores and uppercase letters are rather uncommon, so mostconfigurations should probably assign value ^[a-z]+(\.[a-z][a-z0-9]*)*$ toformat for module PackageName.

+

Checks that package names conform to a specified pattern.

The default value of format for module PackageName has beenchosen to match the requirements in the JavaLanguage specification and the Sun coding conventions. However,both underscores and uppercase letters are rather uncommon, so mostconfigurations should probably assign value ^[a-z]+(\.[a-z][a-z0-9]*)*$ toformat for module PackageName.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.naming @@ -948,6 +954,12 @@ com.puppycrawl.tools.checkstyle.checks.naming.PatternVariableNameCheck: This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.naming +"

com.puppycrawl.tools.checkstyle.checks.naming

.RecordComponentNameCheck": + Description: | +

Checks that record component names conform to a specified pattern.

+ This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project. +

+ Package: "

com.puppycrawl.tools.checkstyle.checks.naming

" "

com.puppycrawl.tools.checkstyle.checks.naming

.RecordTypeParameterNameCheck": Description: |

Checks that record type parameter names conform to a specified pattern.

@@ -968,7 +980,7 @@ com.puppycrawl.tools.checkstyle.checks.naming.TypeNameCheck: Package: com.puppycrawl.tools.checkstyle.checks.naming com.puppycrawl.tools.checkstyle.checks.regexp.RegexpCheck: Description: | -

Checks that a specified pattern exists, exists lessthan a set number of times, or does not exist in the file.

This check combines all the functionality provided byRegexpHeaderexcept supplying the regular expression from a file.

It differs from them in that it works in multiline mode.Its regular expression can span multiple lines and it checks thisagainst the whole file at once.The others work in singleline mode.Their single or multiple regular expressions can only span one line.They check each of these against each line in the file in turn.

Note: Because of the different mode of operation there may besome changes in the regular expressions used to achieve a particular end.

In multiline mode...

Note: Not all regular expression engines are created equal. Some provide extrafunctions that others do not and some elements of the syntax may vary.This check makes use of thejava.util.regex package; please check its documentation fordetails of how to construct a regular expression to achieve a particulargoal.

Note: When entering a regular expression as a parameter in theXML config file you must also take into account the XML rules. e.g. ifyou want to match a < symbol you need to enter &lt;. The regularexpression should be entered on one line.

+

Checks that a specified pattern exists, exists lessthan a set number of times, or does not exist in the file.

This check combines all the functionality provided byRegexpHeaderexcept supplying the regular expression from a file.

It differs from them in that it works in multiline mode.Its regular expression can span multiple lines and it checks thisagainst the whole file at once.The others work in single-line mode.Their single or multiple regular expressions can only span one line.They check each of these against each line in the file in turn.

Note: Because of the different mode of operation there may besome changes in the regular expressions used to achieve a particular end.

In multiline mode...

Note: Not all regular expression engines are created equal. Some provide extrafunctions that others do not and some elements of the syntax may vary.This check makes use of thejava.util.regex package; please check its documentation fordetails of how to construct a regular expression to achieve a particulargoal.

Note: When entering a regular expression as a parameter in theXML config file you must also take into account the XML rules. e.g. ifyou want to match a < symbol you need to enter &lt;. The regularexpression should be entered on one line.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.regexp @@ -980,25 +992,25 @@ com.puppycrawl.tools.checkstyle.checks.regexp.RegexpMultilineCheck: Package: com.puppycrawl.tools.checkstyle.checks.regexp com.puppycrawl.tools.checkstyle.checks.regexp.RegexpOnFilenameCheck: Description: | -

Checks that a specified pattern matches based on file and/or folder path.It can also be used to verify files match specific namingpatterns not covered by other checks (Ex: properties, xml, etc.).

When customizing the check, the properties are applied in a specific order.The fileExtensions property first picks only files that match any of thespecific extensions supplied.Once files are matched against the fileExtensions, the match property is thenused in conjunction with the patterns to determine if the check is lookingfor a match or mis-match on those files. If the fileNamePattern issupplied, the matching is only applied to the fileNamePattern and not thefolderPattern. If no fileNamePattern is supplied, then matching is appliedto the folderPattern only and will result in all files in a folder to bereported on violations. If no folderPattern is supplied, then all foldersthat checkstyle finds are examined for violations.The ignoreFileNameExtensions property drops the file extension and appliesthe fileNamePattern only to the rest of file name. For example, if the file isnamed 'test.java' and this property is turned on, the pattern is only appliedto 'test'.

If this check is configured with no properties, then the default behaviorof this check is to report file names with spaces in them.When at least one pattern property is supplied, the entire check is underthe user's control to allow them to fully customize the behavior.

It is recommended that if you create your own pattern, to alsospecify a custom violation message. This allows the violation message printedto be clear what the violation is, especially if multiple RegexpOnFilenamechecks are used.Argument 0 for the message populates the check's folderPattern.Argument 1 for the message populates the check's fileNamePattern.The file name is not passed as an argument since it is part of CheckStyle'sdefault violation messages.

+

Checks that a specified pattern matches based on file and/or folder path.It can also be used to verify files match specific namingpatterns not covered by other checks (Ex: properties, xml, etc.).

When customizing the check, the properties are applied in a specific order.The fileExtensions property first picks only files that match any of thespecific extensions supplied.Once files are matched against the fileExtensions, the match property is thenused in conjunction with the patterns to determine if the check is lookingfor a match or mismatch on those files. If the fileNamePattern issupplied, the matching is only applied to the fileNamePattern and not thefolderPattern. If no fileNamePattern is supplied, then matching is appliedto the folderPattern only and will result in all files in a folder to bereported on violations. If no folderPattern is supplied, then all foldersthat checkstyle finds are examined for violations.The ignoreFileNameExtensions property drops the file extension and appliesthe fileNamePattern only to the rest of file name. For example, if the file isnamed 'test.java' and this property is turned on, the pattern is only appliedto 'test'.

If this check is configured with no properties, then the default behaviorof this check is to report file names with spaces in them.When at least one pattern property is supplied, the entire check is underthe user's control to allow them to fully customize the behavior.

It is recommended that if you create your own pattern, to alsospecify a custom violation message. This allows the violation message printedto be clear what the violation is, especially if multiple RegexpOnFilenamechecks are used.Argument 0 for the message populates the check's folderPattern.Argument 1 for the message populates the check's fileNamePattern.The file name is not passed as an argument since it is part of CheckStyle'sdefault violation messages.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.regexp com.puppycrawl.tools.checkstyle.checks.regexp.RegexpSinglelineCheck: Description: | -

Checks that a specified pattern matches a single line in any file type.

Rationale: This check can be used to prototype checks and tofind common bad practice such as calling ex.printStacktrace(), System.out.println(), System.exit(), etc.

+

Checks that a specified pattern matches a single-line in any file type.

Rationale: This check can be used to prototype checks and tofind common bad practice such as calling ex.printStacktrace(), System.out.println(), System.exit(), etc.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.regexp com.puppycrawl.tools.checkstyle.checks.regexp.RegexpSinglelineJavaCheck: Description: | -

Checks that a specified pattern matches a single line in Java files.

This class is variation onRegexpSingleline for detectingsingle lines that match a supplied regular expression in Java files. It supportssuppressing matches in Java comments.

+

Checks that a specified pattern matches a single-line in Java files.

This class is variation onRegexpSingleline for detectingsingle-lines that match a supplied regular expression in Java files. It supportssuppressing matches in Java comments.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.regexp com.puppycrawl.tools.checkstyle.checks.sizes.AnonInnerLengthCheck: Description: | -

Checks for long anonymous inner classes.

Rationale: If an anonymous inner class becomes very long it is hardto understand and to see the flow of the method where the class isdefined. Therefore long anonymous inner classes should usually berefactored into a named inner class. See also Bloch, EffectiveJava, p. 93.

+

Checks for long anonymous inner classes.

Rationale: If an anonymous inner class becomes very long it is hardto understand and to see the flow of the method where the class isdefined. Therefore, long anonymous inner classes should usually berefactored into a named inner class. See also Bloch, EffectiveJava, p. 93.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.sizes @@ -1010,13 +1022,13 @@ com.puppycrawl.tools.checkstyle.checks.sizes.ExecutableStatementCountCheck: Package: com.puppycrawl.tools.checkstyle.checks.sizes com.puppycrawl.tools.checkstyle.checks.sizes.FileLengthCheck: Description: | -

Checks for long source files.

Rationale: If a source file becomes very long it is hard tounderstand. Therefore long classes should usually be refactoredinto several individual classes that focus on a specific task.

+

Checks for long source files.

Rationale: If a source file becomes very long it is hard tounderstand. Therefore, long classes should usually be refactoredinto several individual classes that focus on a specific task.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.sizes com.puppycrawl.tools.checkstyle.checks.sizes.LambdaBodyLengthCheck: Description: | -

Checks lambda body length.

Rationale: Similar to anonymous inner classes, if lambda body becomes very longit is hard to understand and to see the flow of the methodwhere the lambda is defined. Therefore long lambda bodyshould usually be extracted to method.

+

Checks lambda body length.

Rationale: Similar to anonymous inner classes, if lambda body becomes very longit is hard to understand and to see the flow of the methodwhere the lambda is defined. Therefore, long lambda bodyshould usually be extracted to method.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.sizes @@ -1034,7 +1046,7 @@ com.puppycrawl.tools.checkstyle.checks.sizes.MethodCountCheck: Package: com.puppycrawl.tools.checkstyle.checks.sizes com.puppycrawl.tools.checkstyle.checks.sizes.MethodLengthCheck: Description: | -

Checks for long methods and constructors.

Rationale: If a method becomes very long it is hard tounderstand. Therefore long methods should usually be refactored intoseveral individual methods that focus on a specific task.

+

Checks for long methods and constructors.

Rationale: If a method becomes very long it is hard tounderstand. Therefore, long methods should usually be refactored intoseveral individual methods that focus on a specific task.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.sizes @@ -1056,10 +1068,9 @@ com.puppycrawl.tools.checkstyle.checks.sizes.RecordComponentNumberCheck: This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.sizes -".Caching SupportCheck": {} -".Localisation SupportCheck": {} -".Base directory supportCheck": {} +".Localization SupportCheck": {} ".Enable External DTD loadCheck": {} +".Property chaining supportCheck": {} com.puppycrawl.tools.checkstyle.checks.whitespace.EmptyForInitializerPadCheck: Description: |

Checks the padding of an empty for initializer; that is whethera white space is required at an empty for initializer, or such whitespace is forbidden. No check occurs if there is a line wrap at theinitializer, as in


for (
; i < j; i++, j--)

@@ -1074,7 +1085,7 @@ com.puppycrawl.tools.checkstyle.checks.whitespace.EmptyForIteratorPadCheck: Package: com.puppycrawl.tools.checkstyle.checks.whitespace com.puppycrawl.tools.checkstyle.checks.whitespace.EmptyLineSeparatorCheck: Description: | -

Checks for empty line separators after header, package, all import declarations,fields, constructors, methods, nested classes,static initializers and instance initializers.

ATTENTION: empty line separator is required between token siblings,not after line where token is found.If token does not have same type sibling then empty lineis required at its end (for example for CLASS_DEF it is after '}').Also, trailing comments are skipped.

ATTENTION: violations from multiple empty lines cannot be suppressed via XPath:#8179.

+

Checks for empty line separators before package, all import declarations,fields, constructors, methods, nested classes,static initializers and instance initializers.

Checks for empty line separators before not only statements butimplementation and documentation comments and blocks as well.

ATTENTION: empty line separator is required between token siblings,not after line where token is found.If token does not have a sibling of the same type, then empty lineis required at its end (for example for CLASS_DEF it is after '}').Also, trailing comments are skipped.

ATTENTION: violations from multiple empty lines cannot be suppressed via XPath:#8179.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.whitespace @@ -1086,7 +1097,7 @@ com.puppycrawl.tools.checkstyle.checks.whitespace.FileTabCharacterCheck: Package: com.puppycrawl.tools.checkstyle.checks.whitespace com.puppycrawl.tools.checkstyle.checks.whitespace.GenericWhitespaceCheck: Description: | -

Checks that the whitespace around the Generic tokens (angle brackets)"<" and ">" are correct to the typical convention.The convention is not configurable.

Left angle bracket ("<"):

Right angle bracket (">"):

+

Checks that the whitespace around the Generic tokens (angle brackets)"<" and ">" are correct to the typical convention.The convention is not configurable.

Left angle bracket ("<"):

Right angle bracket (">"):

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.whitespace @@ -1098,19 +1109,25 @@ com.puppycrawl.tools.checkstyle.checks.whitespace.MethodParamPadCheck: Package: com.puppycrawl.tools.checkstyle.checks.whitespace com.puppycrawl.tools.checkstyle.checks.whitespace.NoLineWrapCheck: Description: | -

Checks that chosen statements are not line-wrapped. By default thisCheck restricts wrapping import and package statements, but it's possible to checkany statement.

+

Checks that chosen statements are not line-wrapped. By default, thisCheck restricts wrapping import and package statements, but it's possible to checkany statement.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.whitespace com.puppycrawl.tools.checkstyle.checks.whitespace.NoWhitespaceAfterCheck: Description: | -

Checks that there is no whitespace after a token. More specifically,it checks that it is not followed by whitespace, or (if linebreaksare allowed) all characters on the line after are whitespace. Toforbid linebreaks after a token, set property allowLineBreaks to false.

The check processesARRAY_DECLARATORandINDEX_OPtokens specially from other tokens. Actually it is checked that there isno whitespace before this tokens, not after them.Space after theANNOTATIONS beforeARRAY_DECLARATORandINDEX_OPwill be ignored.

+

Checks that there is no whitespace after a token. More specifically,it checks that it is not followed by whitespace, or (if linebreaksare allowed) all characters on the line after are whitespace. Toforbid linebreaks after a token, set property allowLineBreaks to false.

The check processesARRAY_DECLARATORandINDEX_OPtokens specially from other tokens. Actually it is checked that there isno whitespace before these tokens, not after them.Space after theANNOTATIONS beforeARRAY_DECLARATORandINDEX_OPwill be ignored.

If the annotation is between the type and the array,like char @NotNull [] param, the check will skipvalidation for spaces.

Note: This check processes theLITERAL_SYNCHRONIZED token only when it appears as a part of asynchronized statement, i.e. synchronized(this) {}.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.whitespace com.puppycrawl.tools.checkstyle.checks.whitespace.NoWhitespaceBeforeCheck: Description: | -

Checks that there is no whitespace before a token. Morespecifically, it checks that it is not preceded with whitespace, or(if linebreaks are allowed) all characters on the line before arewhitespace. To allow linebreaks before a token, set propertyallowLineBreaks to true. No check occursbefore semi-colons in empty for loop initializers or conditions.

+

Checks that there is no whitespace before a token. Morespecifically, it checks that it is not preceded with whitespace, or(if linebreaks are allowed) all characters on the line before arewhitespace. To allow linebreaks before a token, set propertyallowLineBreaks to true. No check occursbefore semicolons in empty for loop initializers or conditions.

+ This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project. +

+ Package: com.puppycrawl.tools.checkstyle.checks.whitespace +com.puppycrawl.tools.checkstyle.checks.whitespace.NoWhitespaceBeforeCaseDefaultColonCheck: + Description: | +

Checks that there is no whitespace before the colon in a switch block.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.whitespace @@ -1122,7 +1139,7 @@ com.puppycrawl.tools.checkstyle.checks.whitespace.OperatorWrapCheck: Package: com.puppycrawl.tools.checkstyle.checks.whitespace com.puppycrawl.tools.checkstyle.checks.whitespace.ParenPadCheck: Description: | -

Checks the policy on the padding of parentheses; that is whether aspace is required after a left parenthesis and before a rightparenthesis, or such spaces are forbidden. No check occurs atthe right parenthesis after an empty for iterator, at the leftparenthesis before an empty for initialization, or at the rightparenthesis of a try-with-resources resource specification wherethe last resource variable has a trailing semi-colon.Use Check EmptyForIteratorPad to validate empty for iterators andEmptyForInitializerPad to validate empty for initializers.Typecasts are also not checked, as there isTypecastParenPad to validate them.

+

Checks the policy on the padding of parentheses; that is whether aspace is required after a left parenthesis and before a rightparenthesis, or such spaces are forbidden. No check occurs atthe right parenthesis after an empty for iterator, at the leftparenthesis before an empty for initialization, or at the rightparenthesis of a try-with-resources resource specification wherethe last resource variable has a trailing semicolon.Use Check EmptyForIteratorPad to validate empty for iterators andEmptyForInitializerPad to validate empty for initializers.Typecasts are also not checked, as there isTypecastParenPad to validate them.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.whitespace @@ -1134,7 +1151,7 @@ com.puppycrawl.tools.checkstyle.checks.whitespace.SeparatorWrapCheck: Package: com.puppycrawl.tools.checkstyle.checks.whitespace com.puppycrawl.tools.checkstyle.checks.whitespace.SingleSpaceSeparatorCheck: Description: | -

Checks that non-whitespace characters are separated by no more than onewhitespace. Separating characters by tabs or multiple spaces will bereported. Currently the check doesn't permit horizontal alignment. To inspectwhitespaces before and after comments, set the propertyvalidateComments to true.

Setting validateComments to false will ignore cases like:


int i; // Multiple whitespaces before comment tokens will be ignored.
private void foo(int /* whitespaces before and after block-comments will be
ignored */ i) {

Sometimes, users like to space similar items on different lines to the samecolumn position for easier reading. This feature isn't supported by thischeck, so both braces in the following case will be reported as violations.


public long toNanos(long d) { return d; } // 2 violations
public long toMicros(long d) { return d / (C1 / C0); }

+

Checks that non-whitespace characters are separated by no more than onewhitespace. Separating characters by tabs or multiple spaces will bereported. Currently, the check doesn't permit horizontal alignment. To inspectwhitespaces before and after comments, set the propertyvalidateComments to true.

Setting validateComments to false will ignore cases like:


int i; // Multiple whitespaces before comment tokens will be ignored.
private void foo(int /* whitespaces before and after block-comments will be
ignored */ i) {

Sometimes, users like to space similar items on different lines to the samecolumn position for easier reading. This feature isn't supported by thischeck, so both braces in the following case will be reported as violations.


public long toNanos(long d) { return d; } // 2 violations
public long toMicros(long d) { return d / (C1 / C0); }

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Package: com.puppycrawl.tools.checkstyle.checks.whitespace diff --git a/config/codeclimate_checkstyle.xml b/config/codeclimate_checkstyle.xml index 34bd873..17c7263 100644 --- a/config/codeclimate_checkstyle.xml +++ b/config/codeclimate_checkstyle.xml @@ -125,7 +125,6 @@ - From a6b384683486078b739c2fc5d202c180e4615844 Mon Sep 17 00:00:00 2001 From: Mike Poage Date: Mon, 13 Feb 2023 08:46:42 -0500 Subject: [PATCH 2/4] add Quality context to release image in Circle Config --- .circleci/config.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.circleci/config.yml b/.circleci/config.yml index cb1a64a..29258c1 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -39,6 +39,7 @@ workflows: jobs: - test - release_images: + context: Quality requires: - test filters: From 5a34161fa3e4fd56fbef7089dada69c6be07038c Mon Sep 17 00:00:00 2001 From: Mike Poage Date: Thu, 16 Feb 2023 11:04:10 -0500 Subject: [PATCH 3/4] push to dockerhub instead of GCR --- .circleci/config.yml | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 29258c1..0dcd308 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -25,13 +25,12 @@ jobs: circleci step halt fi - run: make image - - run: echo "$GCR_JSON_KEY" | docker login -u _json_key --password-stdin us.gcr.io + - run: echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" --password-stdin - run: - name: Push image to GCR + name: Push image to Dockerhub command: | - docker tag codeclimate/codeclimate-checkstyle \ - us.gcr.io/code-climate/codeclimate-checkstyle:b$CIRCLE_BUILD_NUM - docker push us.gcr.io/code-climate/codeclimate-checkstyle:b$CIRCLE_BUILD_NUM + make release RELEASE_TAG="b$CIRCLE_BUILD_NUM" + make release RELEASE_TAG="$(echo $CIRCLE_BRANCH | grep -oP 'channel/\K[\w\-]+')" workflows: version: 2 From 6cd6154a4c25e016dd2cb1f9999d27f2210e8c5c Mon Sep 17 00:00:00 2001 From: Mike Poage Date: Thu, 16 Feb 2023 11:20:37 -0500 Subject: [PATCH 4/4] add release command to Makefile --- Makefile | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 2cd94bb..4456deb 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,13 @@ -.PHONY: image test +.PHONY: image test release IMAGE_NAME ?= codeclimate/codeclimate-checkstyle +RELEASE_REGISTRY ?= codeclimate DOCKER_RUN_MOUNTED = docker run --rm --user=root -w /usr/src/app -v $(PWD):/usr/src/app +ifndef RELEASE_TAG +override RELEASE_TAG = latest +endif + image: docker build --rm -t $(IMAGE_NAME) . @@ -15,3 +20,7 @@ test: image upgrade: $(DOCKER_RUN_MOUNTED) $(IMAGE_NAME) ./bin/upgrade.sh $(DOCKER_RUN_MOUNTED) $(IMAGE_NAME) ./bin/scrape-docs + +release: + docker tag $(IMAGE_NAME) $(RELEASE_REGISTRY)/codeclimate-checkstyle:$(RELEASE_TAG) + docker push $(RELEASE_REGISTRY)/codeclimate-checkstyle:$(RELEASE_TAG)