From 157cf25fa6e06160c3bdac616b7e55beb43d3471 Mon Sep 17 00:00:00 2001 From: Will Fleming Date: Thu, 5 Mar 2020 17:15:17 -0500 Subject: [PATCH 1/2] Upgrade to 8.30 Tweaked Makefile to run container as root for these tasks so it can overwrite the mounted files. --- CHECKSTYLE_VERSION | 2 +- Dockerfile | 4 +- Makefile | 2 +- bin/install-checkstyle.sh | 2 +- check_contents.yml | 194 ++++++++++++++++++++++---------------- 5 files changed, 117 insertions(+), 87 deletions(-) diff --git a/CHECKSTYLE_VERSION b/CHECKSTYLE_VERSION index f5e5cc5..b0aabe1 100644 --- a/CHECKSTYLE_VERSION +++ b/CHECKSTYLE_VERSION @@ -1 +1 @@ -8.26 +8.30 diff --git a/Dockerfile b/Dockerfile index e536cb5..0770ae8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -19,8 +19,8 @@ RUN { \ 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 8u222 -ENV JAVA_ALPINE_VERSION 8.222.10-r0 +ENV JAVA_VERSION 8u242 +ENV JAVA_ALPINE_VERSION 8.242.08-r0 RUN set -x \ && apk update && apk add --no-cache --update \ diff --git a/Makefile b/Makefile index 2bfa197..2cd94bb 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ .PHONY: image test IMAGE_NAME ?= codeclimate/codeclimate-checkstyle -DOCKER_RUN_MOUNTED = docker run --rm -w /usr/src/app -v $(PWD):/usr/src/app +DOCKER_RUN_MOUNTED = docker run --rm --user=root -w /usr/src/app -v $(PWD):/usr/src/app image: docker build --rm -t $(IMAGE_NAME) . diff --git a/bin/install-checkstyle.sh b/bin/install-checkstyle.sh index 6867acc..5ea8b34 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.26/checkstyle-8.26-all.jar' +URL='https://github.com/checkstyle/checkstyle/releases/download/checkstyle-8.30/checkstyle-8.30-all.jar' wget -O /usr/local/bin/checkstyle.jar $URL diff --git a/check_contents.yml b/check_contents.yml index 86b3396..b19cabd 100644 --- a/check_contents.yml +++ b/check_contents.yml @@ -1,43 +1,43 @@ --- com.puppycrawl.tools.checkstyle.checks.annotation.AnnotationLocationCheck: Description: | -

Check location of annotation on language elements.By default, Check enforce to locate annotations immediately after documentation blockand before target element, annotation should be located on separate line from targetelement. This check also verifies that the annotations are on the same indenting level asthe annotated element if they are not on the same line.

Attention: Elements that cannot have JavaDoc comments like local variables are not in thescope of this check even though a token type like VARIABLE_DEF would matchthem.

Attention: Annotations among modifiers are ignored (looks like false-negative)as there might be a problem with annotations for return types:

public @Nullable Long getStartTimeOrNull() { ... }

Such annotations are better to keep close to type.Due to limitations, Checkstyle can not examine the target of an annotation.

Example:


@Override
@Nullable
public String getNameIfPresent() { ... }

+

Checks location of annotation on language elements.By default, Check enforce to locate annotations immediately after documentation blockand before target element, annotation should be located on separate line from targetelement. This check also verifies that the annotations are on the same indenting level asthe annotated element if they are not on the same line.

Attention: Elements that cannot have JavaDoc comments like local variables are not in thescope of this check even though a token type like VARIABLE_DEF would matchthem.

Attention: Annotations among modifiers are ignored (looks like false-negative)as there might be a problem with annotations for return types:

public @Nullable Long getStartTimeOrNull() { ... }

Such annotations are better to keep close to type.Due to limitations, Checkstyle can not examine the target of an annotation.

Example:


@Override
@Nullable
public String getNameIfPresent() { ... }

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.AnnotationOnSameLineCheck: Description: | -

The check does verifying that annotations are located on the same line with their targets.Verifying with this check is not good practice, but it is using by some style guides.

+

Checks that annotations are located on the same line with their targets.Verifying with this check is not good practice, but it is using by some style guides.

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.AnnotationUseStyleCheck: Description: | -

This check controls the style with the usage of annotations.

Annotations have three element styles starting with the least verbose.

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

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

Using the ElementStyle.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 ElementStyle.COMPACT_NO_ARRAY style is less verbose.It is similar to the ElementStyle.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 ClosingParens.ALWAYS type.To never have ending parenthesis use the ClosingParens.NEVER type.To not enforce a closing parenthesis preference a ClosingParens.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 TrailingArrayComma.ALWAYS type.To never have a trailing comma use the TrailingArrayComma.NEVER type.To not enforce a trailing array comma preference a TrailingArrayComma.IGNOREtype is provided.Set this through the trailingArrayComma property.

By default the ElementStyle is set to COMPACT_NO_ARRAY,the TrailingArrayComma is set to NEVER,and the ClosingParens 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 ElementStyle.IGNORE type is provided.The desired style can be set through the elementStyle property.

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

Using the ElementStyle.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 ElementStyle.COMPACT_NO_ARRAY style is less verbose.It is similar to the ElementStyle.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 ClosingParens.ALWAYS type.To never have ending parenthesis use the ClosingParens.NEVER type.To not enforce a closing parenthesis preference a ClosingParens.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 TrailingArrayComma.ALWAYS type.To never have a trailing comma use the TrailingArrayComma.NEVER type.To not enforce a trailing array comma preference a TrailingArrayComma.IGNOREtype is provided.Set this through the trailingArrayComma property.

By default the ElementStyle is set to COMPACT_NO_ARRAY,the TrailingArrayComma is set to NEVER,and the ClosingParens 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 both the @Deprecated annotation is presentand the @deprecated javadoc tag are present when either one 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 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>

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.MissingOverrideCheck: Description: | -

Verifies that the @Override annotation is presentwhen the @inheritDoc javadoc tag is present.

Rationale: The @Override annotation helpscompiler tools ensure that an override is actually occurring. It isquite easy to accidentally overload a method or hide a static methodand using the @Override annotation points out these problems.

This check will log a violation if using the @inheritDoc tag on a method thatis not valid (ex: private, or static method).

There is a slight difference between the @Override annotation in Java 5 versusJava 6 and above. In Java 5, any method overridden from an interface cannotbe annotated with @Override. In Java 6 this behavior is allowed.

As a result of the aforementioned difference between Java 5 and Java 6, aproperty called javaFiveCompatibility is available. Thisproperty will only check classes, interfaces, etc. that do not contain theextends or implements keyword or are not anonymous classes. This means itonly checks methods overridden from java.lang.Object.Java 5 Compatibility mode severely limits this check. It is recommended toonly use it on Java 5 source.

+

Verifies that the @Override annotation is presentwhen the @inheritDoc javadoc tag is present.

Rationale: The @Override annotation helpscompiler tools ensure that an override is actually occurring. It isquite easy to accidentally overload a method or hide a static methodand using the @Override annotation points out these problems.

This check will log a violation if using the @inheritDoc tag on a method thatis not valid (ex: private, or static method).

There is a slight difference between the @Override annotation in Java 5 versusJava 6 and above. In Java 5, any method overridden from an interface cannotbe annotated with @Override. In Java 6 this behavior is allowed.

As a result of the aforementioned difference between Java 5 and Java 6, aproperty called javaFiveCompatibility is available. Thisproperty will only check classes, interfaces, etc. that do not contain theextends or implements keyword or are not anonymous classes. This means itonly checks methods overridden from java.lang.Object.Java 5 Compatibility mode severely limits this check. It is recommended toonly use it on Java 5 source.

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.PackageAnnotationCheck: Description: | -

This check makes sure that all package annotations are in thepackage-info.java file.

According to the Java Language Specification.

The JLS does not enforce the placement of package annotations.This placement may vary based on implementation. The JLSdoes highly recommend that all package annotations areplaced in the package-info.java file.See Java Language Specification, §7.4.1.

+

Checks that all package annotations are in the package-info.java file.

According to the Java Language Specification.

The JLS does not enforce the placement of package annotations.This placement may vary based on implementation. The JLSdoes highly recommend that all package annotations areplaced in the package-info.java file.See Java Language Specification, §7.4.1.

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.SuppressWarningsCheck: Description: | -

This check allows you to specify what warnings that@SuppressWarnings is not allowed to suppress.You can also specify a list of TokenTypes thatthe configured warning(s) cannot be suppressed on.

Limitations: This check does not consider conditionalsinside the @SuppressWarnings annotation.

For example:@SuppressWarnings((false) ? (true) ? "unchecked" : "foo" : "unused").According to the above example, the "unused" warning is being suppressednot the "unchecked" or "foo" warnings. All of these warnings will beconsidered and matched against regardless of what the conditionalevaluates to.The check also does not support code like @SuppressWarnings("un" + "used"),@SuppressWarnings((String) "unused") or@SuppressWarnings({('u' + (char)'n') + (""+("used" + (String)"")),}).

By default, any warning specified will be disallowed onall legal TokenTypes unless otherwise specified viathe tokens property.

Also, by default warnings that are empty strings or allwhitespace (regex: ^$|^\s+$) are flagged. By specifying,the format property these defaults no longer apply.

This check can be configured so that the "unchecked"and "unused" warnings cannot be suppressed onanything but variable and parameter declarations.See below of an example.

+

Allows to specify what warnings that@SuppressWarningsis not allowed to suppress.You can also specify a list of TokenTypes thatthe configured warning(s) cannot be suppressed on.

Limitations: This check does not consider conditionalsinside the @SuppressWarnings annotation.

For example:@SuppressWarnings((false) ? (true) ? "unchecked" : "foo" : "unused").According to the above example, the "unused" warning is being suppressednot the "unchecked" or "foo" warnings. All of these warnings will beconsidered and matched against regardless of what the conditionalevaluates to.The check also does not support code like @SuppressWarnings("un" + "used"),@SuppressWarnings((String) "unused") or@SuppressWarnings({('u' + (char)'n') + (""+("used" + (String)"")),}).

By default, any warning specified will be disallowed onall legal TokenTypes unless otherwise specified viathe tokens property.

Also, by default warnings that are empty strings or allwhitespace (regex: ^$|^\s+$) are flagged. By specifying,the format property these defaults no longer apply.

This check can be configured so that the "unchecked"and "unused" warnings cannot be suppressed onanything but variable and parameter declarations.See below of an example.

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 @@ -49,7 +49,7 @@ com.puppycrawl.tools.checkstyle.checks.SuppressWarningsHolderCheck: Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.blocks.AvoidNestedBlocksCheck: Description: | -

Finds nested blocks, i.e. 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.


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;
}
}

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 @@ -79,13 +79,19 @@ com.puppycrawl.tools.checkstyle.checks.blocks.NeedBracesCheck: Package: com.puppycrawl.tools.checkstyle.checks.blocks com.puppycrawl.tools.checkstyle.checks.blocks.RightCurlyCheck: Description: | -

Checks the placement of right curly braces ('}')for if-else, try-catch-finally blocks, while-loops, for-loops,method definitions, class definitions, constructor definitions,instance and static initialization blocks.For right curly brace of expression blocks please follow issue#5945.

+

Checks the placement of right curly braces ('}') for code blocks.This check supports if-else, try-catch-finally blocks, while-loops, for-loops,method definitions, class definitions, constructor definitions,instance, static initialization blocks, annotation definitions and enum definitions.For right curly brace of expression blocks of arrays, lambdas and class instancesplease follow issue#5945.For right curly brace of enum constant please follow issue#7519.

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.coding.ArrayTrailingCommaCheck: Description: | -

Checks that array initialization contains a trailing comma.


int[] a = new int[]
{
1,
2,
3,
};

The check demands a comma at the end if neither left nor right curly bracesare on the same line as the last element of the array.


return new int[] { 0 };
return new int[] { 0
};
return new int[] {
0 };

Rationale: Putting this comma in makes it easier to change the orderof the elements or add new elements on the end. Main benefit of a trailingcomma is that when you add new entry to an array, no surrounding lines are changed.


{
100000000000000000000,
200000000000000000000, // OK
}

{
100000000000000000000,
200000000000000000000,
300000000000000000000, // Just this line added, no other changes
}

If closing brace is on the same line as training comma, this benefit is gone(as the check does not demand a certain location of curly braces the followingtwo cases will not produce a violation):


{100000000000000000000,
200000000000000000000,} // Trailing comma not needed, line needs to be modified anyway

{100000000000000000000,
200000000000000000000, // Modified line
300000000000000000000,} // Added line

If opening brace is on the same line as training comma there's also (more arguable)problem:


{100000000000000000000, // Line cannot be just duplicated to slightly modify entry
}

{100000000000000000000,
100000000000000000001, // More work needed to duplicate
}

+

Checks that array initialization contains a trailing comma.


int[] a = new int[]
{
1,
2,
3,
};

The check demands a comma at the end if neither left nor right curly bracesare on the same line as the last element of the array.


return new int[] { 0 };
return new int[] { 0
};
return new int[] {
0 };

Rationale: Putting this comma in makes it easier to change the orderof the elements or add new elements on the end. Main benefit of a trailingcomma is that when you add new entry to an array, no surrounding lines are changed.


{
100000000000000000000,
200000000000000000000, // OK
}

{
100000000000000000000,
200000000000000000000,
300000000000000000000, // Just this line added, no other changes
}

If closing brace is on the same line as trailing comma, this benefit is gone(as the check does not demand a certain location of curly braces the followingtwo cases will not produce a violation):


{100000000000000000000,
200000000000000000000,} // Trailing comma not needed, line needs to be modified anyway

{100000000000000000000,
200000000000000000000, // Modified line
300000000000000000000,} // Added line

If opening brace is on the same line as trailing comma there's also (more arguable)problem:


{100000000000000000000, // Line cannot be just duplicated to slightly modify entry
}

{100000000000000000000,
100000000000000000001, // More work needed to duplicate
}

+ 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.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.

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 @@ -95,15 +101,21 @@ com.puppycrawl.tools.checkstyle.checks.coding.AvoidInlineConditionalsCheck: 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.AvoidNoArgumentSuperConstructorCallCheck: + Description: | +

Checks if call to superclass constructor without arguments is present.Such invocation is redundant because constructor body implicitlybegins with a superclass constructor invocation super();See specification for detailed information.

+ 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.CovariantEqualsCheck: Description: | -

Checks that classes which define a covariant equals() methodalso override method equals(Object).

Covariant equals() - method that is similar to equals(Object),but with a covariant parameter type (any subtype of Object).

Notice: the enums are also checked, eventhough they cannot override equals(Object). The reason isto point out that implementing equals() in enums is considered anawful practice: it may cause having two different enum values that are equal usingcovariant enum method, and not equal when compared normally.

Inspired by Finding Bugs is Easy, chapter '2.3.1 Bad Covariant Definition of Equals (Eq)':

Java classes may override the equals(Object) method to definea predicate for object equality. This method is used by many of the Java runtimelibrary classes; for example, to implement generic containers.

Programmers sometimes mistakenly use the type of their class Fooas the type of the parameter to equals():


public boolean equals(Foo obj) {...}

This covariant version of equals() does not override the version in theObject class, and it may lead to unexpected behavior at runtime,especially if the class is used with one of the standard collection classeswhich expect that the standard equals(Object) method is overridden.

This kind of bug is not obvious because it looks correct, and in circumstances wherethe class is accessed through the references of the class type (rather than a supertype),it will work correctly. However, the first time it is used in a container,the behavior might be mysterious. For these reasons, this type of bug can eludetesting and code inspections.

+

Checks that classes which define a covariant equals() methodalso override method equals(Object).

Covariant equals() - method that is similar to equals(Object),but with a covariant parameter type (any subtype of Object).

Notice: the enums are also checked, eventhough they cannot override equals(Object). The reason isto point out that implementing equals() in enums is considered anawful practice: it may cause having two different enum values that are equal usingcovariant enum method, and not equal when compared normally.

Inspired by Finding Bugs is Easy, chapter '4.5 Bad Covariant Definition of Equals (Eq)':

Java classes may override the equals(Object) method to definea predicate for object equality. This method is used by many of the Java runtimelibrary classes; for example, to implement generic containers.

Programmers sometimes mistakenly use the type of their class Fooas the type of the parameter to equals():


public boolean equals(Foo obj) {...}

This covariant version of equals() does not override the version in theObject class, and it may lead to unexpected behavior at runtime,especially if the class is used with one of the standard collection classeswhich expect that the standard equals(Object) method is overridden.

This kind of bug is not obvious because it looks correct, and in circumstances wherethe class is accessed through the references of the class type (rather than a supertype),it will work correctly. However, the first time it is used in a container,the behavior might be mysterious. For these reasons, this type of bug can eludetesting and code inspections.

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.DeclarationOrderCheck: Description: | -

Checks the order in which parts of the class or interface declaration are defined.

According to Code Conventions for the Java Programming Language , the partsof a class or interface declaration should appear in the followingorder:

  1. Class (static) variables. First the public class variables, thenprotected, then package level (no access modifier), and thenprivate.
  2. Instance variables. First the public class variables, thenprotected, then package level (no access modifier), and thenprivate.
  3. Constructors
  4. Methods

Purpose of ignore* option is to ignore related violations,however it still impacts on other class members.

ATTENTION: the check skips class fields which haveforward referencesfrom validation due to the fact that we have Checkstyle's limitations to clearlydetect user intention of fields location and grouping. For example:


public class A {
private double x = 1.0;
private double y = 2.0;
public double slope = x / y; // will be skipped from validation due to forward reference
}

+

Checks that the parts of a class or interface declaration appear in the ordersuggested by theCode Conventions for the Java Programming Language.

According to Code Conventions for the Java Programming Language , the partsof a class or interface declaration should appear in the followingorder:

  1. Class (static) variables. First the public class variables, thenprotected, then package level (no access modifier), and thenprivate.
  2. Instance variables. First the public class variables, thenprotected, then package level (no access modifier), and thenprivate.
  3. Constructors
  4. Methods

Purpose of ignore* option is to ignore related violations,however it still impacts on other class members.

ATTENTION: the check skips class fields which haveforward referencesfrom validation due to the fact that we have Checkstyle's limitations to clearlydetect user intention of fields location and grouping. For example:


public class A {
private double x = 1.0;
private double y = 2.0;
public double slope = x / y; // will be skipped from validation due to forward reference
}

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 @@ -115,7 +127,7 @@ com.puppycrawl.tools.checkstyle.checks.coding.DefaultComesLastCheck: Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.EmptyStatementCheck: Description: | -

Detects empty statements (standalone {@code ";"} semicolon).Empty statements often introduce bugs that are hard to spot, such as in


if (someCondition);
doConditionalStuff();
doUnconditionalStuff();

+

Detects empty statements (standalone ";" semicolon).Empty statements often introduce bugs that are hard to spot, such as in


if (someCondition);
doConditionalStuff();
doUnconditionalStuff();

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 @@ -139,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. Bydefault the text "fallthru", "fall through", "fallthrough","falls through" and "fallsthrough" are recognized (casesensitive). The comment containing these words must be all on one line, and mustbe on the last non-empty line before thecase triggering the warning or onthe same line before the case(ugly, but possible).


switch (i) {
case 0:
i++; // fall through

case 1:
i++;
// falls through
case 2:
case 3:
case 4: {
i++;
}
// fallthrough
case 5:
i++;
/* fallthru */case 6:
i++
break;
}

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

The following fragment of code will NOT trigger the check,because of the comment "fallthru" and absence of any Java codein case 5.


case 3:
x = 2;
// fallthru
case 4:
case 5:
case 6:
break;

+

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).


switch (i) {
case 0:
i++; // fall through

case 1:
i++;
// falls through
case 2:
case 3:
case 4: {
i++;
}
// fallthrough
case 5:
i++;
/* fallthru */case 6:
i++;
// fall-through
case 7:
i++;
break;
}

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

The following fragment of code will NOT trigger the check,because of the comment "fallthru" or any Java codein case 5 are absent.

case 3:x = 2;// fallthrucase 4:case 5: // violationcase 6:break;

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 @@ -169,7 +181,7 @@ com.puppycrawl.tools.checkstyle.checks.coding.IllegalInstantiationCheck: Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.IllegalThrowsCheck: Description: | -

This check can be used to ensure that types are not declaredto be thrown. Declaring that a method throws java.lang.Error orjava.lang.RuntimeException is almost never acceptable.

+

Checks that specified types are not declared to be thrown.Declaring that a method throws java.lang.Error orjava.lang.RuntimeException is almost never acceptable.

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 @@ -181,7 +193,7 @@ com.puppycrawl.tools.checkstyle.checks.coding.IllegalTokenCheck: Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.IllegalTokenTextCheck: Description: | -

Checks specified tokens text for matching an illegal pattern fromformat property. 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 @@ -211,13 +223,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.

+

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 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: | -

Check for ensuring 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++;
}

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 @@ -235,19 +247,25 @@ com.puppycrawl.tools.checkstyle.checks.coding.MultipleVariableDeclarationsCheck: Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.NestedForDepthCheck: Description: | -

Restricts nested for blocks to a specified depth(default = 1).

+

Restricts nested for blocks to a specified depth.

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.NestedIfDepthCheck: Description: | -

Restricts nested if-else blocks to a specified depth (default = 1).

+

Restricts nested if-else blocks to a specified depth.

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.NestedTryDepthCheck: Description: | -

Restricts nested try blocks to a specified depth (default = 1).

+

Restricts nested try-catch-finally blocks to a specified depth.

+ 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.NoArrayTrailingCommaCheck: + Description: | +

Checks that array initialization do not contain a trailing comma.Rationale: JLS allows trailing commas in arrays and enumerations, but does not allowthem in other locations. To unify the coding style, the use of trailing commas shouldbe prohibited.


int[] foo = new int[] {
1,
2
};

The check demands that there should not be any comma after the last element of an array.


String[] foo = new String[] {
"FOO",
"BAR", //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 @@ -257,9 +275,15 @@ com.puppycrawl.tools.checkstyle.checks.coding.NoCloneCheck: 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.NoEnumTrailingCommaCheck: + Description: | +

Checks that enum definition does not contain a trailing comma.Rationale: JLS allows trailing commas in arrays and enumerations, but does not allowthem in other locations. To unify the coding style, the use of trailing commas shouldbe prohibited.


enum Foo1 {
FOO,
BAR;
}

The check demands that there should not be any comma after last constant inenum definition.


enum Foo1 {
FOO,
BAR, //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 com.puppycrawl.tools.checkstyle.checks.coding.NoFinalizerCheck: Description: | -

Verifies there are no finalize() methodsdefined in a class.

See Object.finalize()

Rationale: Finalizers are unpredictable, often dangerous, and generally unnecessary.Their use can cause erratic behavior, poor performance, and portability problems.For more information for the finalize method and its issues, see Effective Java:Programming Language Guide Third Edition by Joshua Bloch, §8.

+

Checks that there is no method finalize with zero parameters.

See Object.finalize()

Rationale: Finalizers are unpredictable, often dangerous, and generally unnecessary.Their use can cause erratic behavior, poor performance, and portability problems.For more information for the finalize method and its issues, see Effective Java:Programming Language Guide Third Edition by Joshua Bloch, §8.

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 @@ -295,7 +319,7 @@ com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck: Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.ReturnCountCheck: Description: | -

Restricts the number of return statements in methods, constructors and lambda expressions(2 by default). Ignores specified methods (equals() by default).

max property will only check returns in methods and lambdas that return a specificvalue (Ex: 'return 1;').

maxForVoid property will only check returns in methods, constructors, and lambdasthat have no return type (IE 'return;').It will only count visible return statements. Return statements not normally written, butimplied, at the end of the method/constructor definition will not be taken into account.To disallow "return;" in void return type methods, use a value of 0.

Rationale: Too many return points can mean that code isattempting to do too much or may be difficult to understand.

+

Restricts the number of return statements in methods, constructors and lambda expressions.Ignores specified methods (equals by default).

max property will only check returns in methods and lambdas that return a specificvalue (Ex: 'return 1;').

maxForVoid property will only check returns in methods, constructors, and lambdasthat have no return type (IE 'return;').It will only count visible return statements. Return statements not normally written, butimplied, at the end of the method/constructor definition will not be taken into account.To disallow "return;" in void return type methods, use a value of 0.

Rationale: Too many return points can mean that code isattempting to do too much or may be difficult to understand.

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 @@ -307,13 +331,13 @@ com.puppycrawl.tools.checkstyle.checks.coding.SimplifyBooleanExpressionCheck: Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.SimplifyBooleanReturnCheck: Description: | -

Checks for over-complicated boolean return statements. For examplethe following code


if (valid())
return false;
else
return true;

could be written as


return !valid();

The idea for this Check has been shamelessly stolen from theequivalent PMD rule.

+

Checks for over-complicated boolean return statements. For examplethe following code


if (valid())
return false;
else
return true;

could be written as


return !valid();

The idea for this Check has been shamelessly stolen from theequivalent PMD rule.

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.StringLiteralEqualityCheck: Description: | -

Checks that string literals are not used with == or!=.

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 @@ -325,7 +349,7 @@ com.puppycrawl.tools.checkstyle.checks.coding.SuperCloneCheck: Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.SuperFinalizeCheck: Description: | -

Checks that an overriding finalize() method invokessuper.finalize(). Does not check native methods, asthey have no possible java defined implementation.

References:How to Handle Java Finalization's Memory-Retention Issues;10 points on finalize method in Java.

+

Checks that an overriding finalize() method invokessuper.finalize(). Does not check native methods, asthey have no possible java defined implementation.

References:How to Handle Java Finalization's Memory-Retention Issues;10 points on finalize method in Java.

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 +385,7 @@ com.puppycrawl.tools.checkstyle.checks.coding.VariableDeclarationUsageDistanceCh Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.design.DesignForExtensionCheck: Description: | -

The check finds classes that are designed for extension (subclass creation).

Nothing wrong could be with founded classes.This check makes sense only for library projects (not application projects)which care of ideal OOP-design to make sure that class works in all cases even misusage.Even in library projects this check most likely will find classes that are designedfor extension by somebody. User needs to use suppressions extensively to got a benefitfrom this check, and keep in suppressions all confirmed/known classes that are deignedfor inheritance intentionally to let the check catch only new classes, and bring this toteam/user attention.

ATTENTION: Only user can decide whether a class is designed for extension or not.The check just shows all classes which are possibly designed for extension.If smth inappropriate is found please use suppression.

ATTENTION: If the method which can be overridden in a subclass has a javadoc comment(a good practice is to explain its self-use of overridable methods) the check will notrise a violation. The violation can also be skipped if the method which can be overriddenin a subclass has one or more annotations that are specified in ignoredAnnotationsoption. Note, that by default @Override annotation is not included in theignoredAnnotations set as in a subclass the method which has the annotation can also beoverridden in its subclass.

Problem is described at "Effective Java, 2nd Edition by Joshua Bloch" book, chapter"Item 17: Design and document for inheritance or else prohibit it".

Some quotes from book:

The class must document its self-use of overridable methods.By convention, a method that invokes overridable methods contains a descriptionof these invocations at the end of its documentation comment. The descriptionbegins with the phrase “This implementation.”
The best solution to this problem is to prohibit subclassing in classes thatare not designed and documented to be safely subclassed.
If a concrete class does not implement a standard interface, then you mayinconvenience some programmers by prohibiting inheritance. If you feel that youmust allow inheritance from such a class, one reasonable approach is to ensurethat the class never invokes any of its overridable methods and to document thisfact. In other words, eliminate the class’s self-use of overridable methods entirely.In doing so, you’ll create a class that is reasonably safe to subclass. Overriding amethod will never affect the behavior of any other method.

The check finds classes that have overridable methods (public or protected methodsthat are non-static, not-final, non-abstract) and have non-empty implementation.

Rationale: This library design style protects superclasses againstbeing broken by subclasses. The downside is that subclasses arelimited in their flexibility, in particular they cannot preventexecution of code in the superclass, but that also means thatsubclasses cannot corrupt the state of the superclass by forgettingto call the superclass's method.

More specifically,it enforces a programming style where superclasses provide empty"hooks" that can be implemented by subclasses.

Example of code that cause violation as it is designed for extension:


public abstract class Plant {
private String roots;
private String trunk;

protected void validate() {
if (roots == null) throw new IllegalArgumentException("No roots!");
if (trunk == null) throw new IllegalArgumentException("No trunk!");
}

public abstract void grow();
}

public class Tree extends Plant {
private List leaves;

@Overrides
protected void validate() {
super.validate();
if (leaves == null) throw new IllegalArgumentException("No leaves!");
}

public void grow() {
validate();
}
}

Example of code without violation:


public abstract class Plant {
private String roots;
private String trunk;

private void validate() {
if (roots == null) throw new IllegalArgumentException("No roots!");
if (trunk == null) throw new IllegalArgumentException("No trunk!");
validateEx();
}

protected void validateEx() { }

public abstract void grow();
}

+

Checks that classes are designed for extension (subclass creation).

Nothing wrong could be with founded classes.This check makes sense only for library projects (not application projects)which care of ideal OOP-design to make sure that class works in all cases even misusage.Even in library projects this check most likely will find classes that are designedfor extension by somebody. User needs to use suppressions extensively to got a benefitfrom this check, and keep in suppressions all confirmed/known classes that are deignedfor inheritance intentionally to let the check catch only new classes, and bring this toteam/user attention.

ATTENTION: Only user can decide whether a class is designed for extension or not.The check just shows all classes which are possibly designed for extension.If smth inappropriate is found please use suppression.

ATTENTION: If the method which can be overridden in a subclass has a javadoc comment(a good practice is to explain its self-use of overridable methods) the check will notrise a violation. The violation can also be skipped if the method which can be overriddenin a subclass has one or more annotations that are specified in ignoredAnnotationsoption. Note, that by default @Override annotation is not included in theignoredAnnotations set as in a subclass the method which has the annotation can also beoverridden in its subclass.

Problem is described at "Effective Java, 2nd Edition by Joshua Bloch" book, chapter"Item 17: Design and document for inheritance or else prohibit it".

Some quotes from book:

The class must document its self-use of overridable methods.By convention, a method that invokes overridable methods contains a descriptionof these invocations at the end of its documentation comment. The descriptionbegins with the phrase “This implementation.”
The best solution to this problem is to prohibit subclassing in classes thatare not designed and documented to be safely subclassed.
If a concrete class does not implement a standard interface, then you mayinconvenience some programmers by prohibiting inheritance. If you feel that youmust allow inheritance from such a class, one reasonable approach is to ensurethat the class never invokes any of its overridable methods and to document thisfact. In other words, eliminate the class’s self-use of overridable methods entirely.In doing so, you’ll create a class that is reasonably safe to subclass. Overriding amethod will never affect the behavior of any other method.

The check finds classes that have overridable methods (public or protected methodsthat are non-static, not-final, non-abstract) and have non-empty implementation.

Rationale: This library design style protects superclasses againstbeing broken by subclasses. The downside is that subclasses arelimited in their flexibility, in particular they cannot preventexecution of code in the superclass, but that also means thatsubclasses cannot corrupt the state of the superclass by forgettingto call the superclass's method.

More specifically,it enforces a programming style where superclasses provide empty"hooks" that can be implemented by subclasses.

Example of code that cause violation as it is designed for extension:


public abstract class Plant {
private String roots;
private String trunk;

protected void validate() {
if (roots == null) throw new IllegalArgumentException("No roots!");
if (trunk == null) throw new IllegalArgumentException("No trunk!");
}

public abstract void grow();
}

public class Tree extends Plant {
private List leaves;

@Overrides
protected void validate() {
super.validate();
if (leaves == null) throw new IllegalArgumentException("No leaves!");
}

public void grow() {
validate();
}
}

Example of code without violation:


public abstract class Plant {
private String roots;
private String trunk;

private void validate() {
if (roots == null) throw new IllegalArgumentException("No roots!");
if (trunk == null) throw new IllegalArgumentException("No trunk!");
validateEx();
}

protected void validateEx() { }

public abstract void grow();
}

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 @@ -379,7 +403,7 @@ com.puppycrawl.tools.checkstyle.checks.design.HideUtilityClassConstructorCheck: Package: com.puppycrawl.tools.checkstyle.checks.design com.puppycrawl.tools.checkstyle.checks.design.InnerTypeLastCheck: Description: | -

Check nested (inner) classes/interfaces are declared at thebottom of the class after all method and field declarations.

+

Checks nested (internal) classes/interfaces are declared at the bottom of theprimary (top-level) class after all method and field declarations.

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 @@ -403,7 +427,7 @@ com.puppycrawl.tools.checkstyle.checks.design.OneTopLevelClassCheck: Package: com.puppycrawl.tools.checkstyle.checks.design com.puppycrawl.tools.checkstyle.checks.design.ThrowsCountCheck: Description: | -

Restricts throws statements to a specified count (4 by default).Methods with "Override" or "java.lang.Override" annotation are skippedfrom validation as current class cannot change signature of these methods.

Rationale: Exceptions form part of a method's interface. Declaring amethod to throw too many differently rooted exceptions makesexception handling onerous and leads to poor programming practicessuch as writing code like catch(Exception ex).4 is the empirical value which is based on reports that we had forthe ThrowsCountCheck over big projects such as OpenJDK.This check also forces developers to put exceptions into a hierarchysuch that in the simplest case, only one type of exception need bechecked for by a caller but any subclasses can be caught specificallyif necessary. For more information on rules for the exceptions andtheir issues, see Effective Java: Programming Language GuideSecond Edition by Joshua Bloch pages 264-273.

ignorePrivateMethods - allows to skip private methods as they donot cause problems for other classes.

+

Restricts throws statements to a specified count.Methods with "Override" or "java.lang.Override" annotation are skippedfrom validation as current class cannot change signature of these methods.

Rationale: Exceptions form part of a method's interface. Declaring amethod to throw too many differently rooted exceptions makesexception handling onerous and leads to poor programming practicessuch as writing code like catch(Exception ex).4 is the empirical value which is based on reports that we had forthe ThrowsCountCheck over big projects such as OpenJDK.This check also forces developers to put exceptions into a hierarchysuch that in the simplest case, only one type of exception need bechecked for by a caller but any subclasses can be caught specificallyif necessary. For more information on rules for the exceptions andtheir issues, see Effective Java: Programming Language GuideSecond Edition by Joshua Bloch pages 264-273.

ignorePrivateMethods - allows to skip private methods as they donot cause problems for other 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.design @@ -433,7 +457,7 @@ com.puppycrawl.tools.checkstyle.filters.SuppressionCommentFilterCheck: Package: com.puppycrawl.tools.checkstyle.filters com.puppycrawl.tools.checkstyle.filters.SuppressionFilterCheck: Description: | -

Filter SuppressionFilter rejectsaudit events for Check violations according toa suppressions XMLdocument in a file. If there is no configuredsuppressions file or the optional is set to true andsuppressions file was not found the Filter accepts all audit events.

+

Filter SuppressionFilter rejectsaudit events for Check violations according toa suppressions XMLdocument in a file. If there is no configuredsuppressions file or the optional is set to true andsuppressions file was not found the Filter accepts all audit events.

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 @@ -445,7 +469,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 supports the followingchecks:

Note, that support for other Checks will be available after resolvingissue 4830.

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 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.

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 @@ -511,7 +535,7 @@ 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 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">

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 @@ -551,51 +575,57 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocBlockTagLocationCheck: 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.JavadocContentLocationCheck: + Description: | +

Checks that the Javadoc content begins from the same positionfor all Javadoc comments in the project. Any leading asterisks and spacesare not counted as the beginning of the content and are therefore ignored.

It is possible to enforce two different styles:

+ 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.JavadocMethodCheck: Description: | -

Since Checkstyle 3.0

Checks the Javadoc of a method or constructor. By default,does not check for unused throws. To allow documentedjava.lang.RuntimeExceptions that are notdeclared, set property allowUndeclaredRTE to true. 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. Violatesexceptions which are declared to be thrown, but for which nothrows tag is present can be suppressed by defining propertyallowMissingThrowsTags. Violatesmethods which return non-void but for which no return tag ispresent can be suppressed by defining propertyallowMissingReturnTag.

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)

The classpath may need to be configured to locate the classinformation. The classpath configuration is dependent on themechanism used to invoke Checkstyle.

+

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, but for which nothrows tag is present by activation of propertyvalidateThrows.

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)

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.JavadocPackageCheck: Description: | -

Since Checkstyle 5.0

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 com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocParagraphCheck: Description: | -

Since Checkstyle 6.0

Checks that:

+

Checks the Javadoc paragraph.

Checks that:

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.JavadocStyleCheck: Description: | -

Since Checkstyle 3.2

Validates Javadoc comments to help ensure they are wellformed. 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 com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTagContinuationIndentationCheck: Description: | -

Since Checkstyle 6.0

Checks the indentation of the continuation lines in at-clauses.

+

Checks the indentation of the continuation lines in at-clauses.

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.JavadocTypeCheck: Description: | -

Since Checkstyle 3.0

Checks Javadoc comments for class and interface 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 for which no param tags arepresent can be suppressed by defining propertyallowMissingParamTags.

+

Checks the Javadoc comments for annotation/enum/class/interface 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 for which no param tags arepresent 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 com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocVariableCheck: Description: | -

Since Checkstyle 3.0

Checks that variables have Javadoc comments. Ignores serialVersionUIDfields.

+

Checks that a variable has a Javadoc comment. Ignores serialVersionUIDfields.

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.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). 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;}

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,43 +643,43 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.MissingJavadocTypeCheck: Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.NonEmptyAtclauseDescriptionCheck: Description: | -

Since Checkstyle 6.0

Checks that the at-clause tag is followed by description.

+

Checks that the at-clause tag is followed by description.

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.SingleLineJavadocCheck: Description: | -

Since Checkstyle 6.0

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

+

Checks that a Javadoc block can fit in a single line and doesn'tcontain at-clauses. Javadoc comment that contains at least one at-clauseshould 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: | -

Since Checkstyle 6.0

Checks that Javadoc 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. Check alsoviolate Javadoc that does not contain first sentence.

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.WriteTagCheck: Description: | -

Since Checkstyle 4.2

Requires user defined JavaDoc tag to be present in javadoc comment withdefined format. To define the format for a tag, set property tagFormat to a regularexpression. Property tagSeverity is used for severity of events when the tag exists.

+

Requires user defined Javadoc tag to be present in Javadoc comment withdefined format. To define the format for a tag, set property tagFormat to a regularexpression. Property tagSeverity is used for severity of events when the tag exists.

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.metrics.BooleanExpressionComplexityCheck: Description: | -

Restrict the number of &&, ||,&, |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: | -

This metric measures the number of instantiations of otherclasses within the given class. 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. 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: | -

The number of other classes a given class relies on. Also thesquare 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 classes a given class relies on. Also thesquare 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 @@ -667,7 +697,7 @@ 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 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.

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 @@ -679,7 +709,7 @@ com.puppycrawl.tools.checkstyle.checks.ArrayTypeStyleCheck: Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.AvoidEscapedUnicodeCharactersCheck: Description: | -

Restrict usingUnicode escapes (such as \u221e).It is possible to allow using escapes fornon-printable, control characters.Also, this check can be configured to allow using escapesif trail comment is present. By the option it is possible toallow using escapes if literal contains only them.

+

Restricts usingUnicode escapes (such as \u221e).It is possible to allow using escapes fornon-printable, control characters.Also, this check can be configured to allow using escapesif trail comment is present. By the option it is possible toallow using escapes if literal contains only 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 @@ -697,13 +727,13 @@ com.puppycrawl.tools.checkstyle.checks.DescendantTokenCheck: Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.FinalParametersCheck: Description: | -

Check that parameters for methods, constructors, catch and for-each blocks arefinal. Interface, abstract, and native methods are not checked: the finalkeyword does not make sense for interface, abstract, and native methodparameters as there is no code that could modify the parameter.

Rationale: Changing the value of parameters during the execution ofthe method's algorithm can be confusing and should be avoided. Agreat way to let the Java compiler prevent this coding style is todeclare parameters final.

+

Checks that parameters for methods, constructors, catch and for-each blocks arefinal. Interface, abstract, and native methods are not checked: the finalkeyword does not make sense for interface, abstract, and native methodparameters as there is no code that could modify the parameter.

Rationale: Changing the value of parameters during the execution ofthe method's algorithm can be confusing and should be avoided. Agreat way to let the Java compiler prevent this coding style is todeclare parameters 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 com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck: Description: | -

Checks correct indentation of Java code.

The idea behind this is that while pretty printers aresometimes convenient for bulk reformats of legacy code, they ofteneither aren't configurable enough or just can't anticipate howformat should be done. Sometimes this is personal preference, othertimes it is practical experience. In any case, this check shouldjust ensure that a minimal set of indentation rules is followed.

+

Checks correct indentation of Java code.

The idea behind this is that while pretty printers aresometimes convenient for bulk reformats of legacy code, they ofteneither aren't configurable enough or just can't anticipate howformat should be done. Sometimes this is personal preference, othertimes it is practical experience. In any case, this check shouldjust ensure that a minimal set of indentation rules is followed.

Basic offset indentation is used for indentation inside code blocks.For any lines that span more than 1, line wrapping indentation is used for thoselines after the first.Brace adjustment, case, and throws indentations are all used only if those specificidentifiers start the line. If, for example, a brace is used in the middle of the line,its indentation will not take effect.All indentations have an accumulative/recursive effect when they are triggered. Ifduring a line wrapping, another code block is found and it doesn't end on that sameline, then the subsequent lines afterwards, in that new code block, are increased ontop of the line wrap and any indentations above it.

Example:


if ((condition1 && condition2)
|| (condition3 && condition4) // line wrap with bigger indentation
||!(condition5 && condition6)) { // line wrap with bigger indentation
field.doSomething() // basic offset
.doSomething() // line wrap
.doSomething( c -> { // line wrap
return c.doSome(); // basic offset
});
}

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 @@ -727,7 +757,7 @@ com.puppycrawl.tools.checkstyle.checks.OuterTypeFilenameCheck: Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.TodoCommentCheck: Description: | -

A check 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 genericregularexpression 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 @@ -739,19 +769,19 @@ com.puppycrawl.tools.checkstyle.checks.TrailingCommentCheck: Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.TranslationCheck: Description: | -

A FileSetCheck that ensuresthe correct translation of code by checking property files forconsistency regarding their keys. Two property filesdescribing one and the same context are consistent if theycontain the same keys. TranslationCheck also can check an existence of requiredtranslations which must exist in project, if requiredTranslationsoption is used.

Consider the following properties file in the same directory:


#messages.properties
hello=Hello
cancel=Cancel

#messages_de.properties
hell=Hallo
ok=OK

The Translation check will find the typo in the German hellokey, the missing ok key in the default resource file and themissing cancel key in the German resource file:


messages_de.properties: Key 'hello' missing.
messages_de.properties: Key 'cancel' missing.
messages.properties: Key 'hell' missing.
messages.properties: Key 'ok' missing.

+

Ensures the correct translation of code by checking property files forconsistency regarding their keys. Two property filesdescribing one and the same context are consistent if theycontain the same keys. TranslationCheck also can check an existence of requiredtranslations which must exist in project, if requiredTranslationsoption is used.

Consider the following properties file in the same directory:


#messages.properties
hello=Hello
cancel=Cancel

#messages_de.properties
hell=Hallo
ok=OK

The Translation check will find the typo in the German hellokey, the missing ok key in the default resource file and themissing cancel key in the German resource file:


messages_de.properties: Key 'hello' missing.
messages_de.properties: Key 'cancel' missing.
messages.properties: Key 'hell' missing.
messages.properties: Key 'ok' missing.

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.UncommentedMainCheck: Description: | -

Checks for 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. With the exception ofthe 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 com.puppycrawl.tools.checkstyle.checks.UniquePropertiesCheck: Description: | -

Checks properties files for duplicate property keys.

Rationale: Multiple property keys usually appear after mergeor rebase of several branches. While there are no problems inruntime, there can be a confusion due to having different valuesfor the duplicated properties.

+

Detects duplicated keys in properties files.

Rationale: Multiple property keys usually appear after mergeor rebase of several branches. While there are no problems inruntime, there can be a confusion due to having different valuesfor the duplicated properties.

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 @@ -775,7 +805,7 @@ 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. 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.

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 @@ -788,7 +818,7 @@ com.puppycrawl.tools.checkstyle.checks.modifier.RedundantModifierCheck: ".OverviewCheck": {} com.puppycrawl.tools.checkstyle.checks.naming.AbbreviationAsWordInNameCheck: Description: | -

The Check validate 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.

+

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.

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 @@ -800,115 +830,115 @@ com.puppycrawl.tools.checkstyle.checks.naming.AbstractClassNameCheck: Package: com.puppycrawl.tools.checkstyle.checks.naming "

com.puppycrawl.tools.checkstyle.checks.naming

.CatchParameterNameCheck": Description: | -

Checks that catch parameter names conform to a format specified by theformat property.

Default pattern has the following characteristic:

+

Checks that catch parameter names conform to a specified pattern.

Default pattern has the following characteristic:

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.ClassTypeParameterNameCheck: Description: | -

Checks that class type parameter names conform to a format specified by the formatproperty.

+

Checks that class type parameter 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.ConstantNameCheck: Description: | -

Checks that constant names conform to a format specified by the format property.A constant is a static and final field or aninterface/annotation field, except serialVersionUID andserialPersistentFields.

+

Checks that constant names conform to a specified pattern.A constant is a static and final field or aninterface/annotation field, except serialVersionUID andserialPersistentFields.

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.InterfaceTypeParameterNameCheck: Description: | -

Checks that interface type parameter names conform to a format specified by the formatproperty.

+

Checks that interface type parameter 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.LambdaParameterNameCheck: Description: | -

Check to verify lambda parameter names.

+

Checks lambda parameter names.

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.LocalFinalVariableNameCheck: Description: | -

Checks that local final variable names conform to a format specifiedby the format property. A catch parameter and resources in try statementsare considered to be a local, final variables.

+

Checks that local final variable names conform to a specified pattern.A catch parameter and resources in try statementsare considered to be a local, final variables.

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.LocalVariableNameCheck: Description: | -

Checks that local, non-final variable names conform to a format specifiedby the format property. A catch parameter is considered to be a local variable.

+

Checks that local, non-final variable names conform to a specified pattern.A catch parameter is considered to be a local variable.

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.MemberNameCheck: Description: | -

Checks that instance variable names conform to a format specified by the format property.

+

Checks that instance variable 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.MethodNameCheck: Description: | -

Checks that method names conform to a format specified by the format property.

Also, checks if a method name has the same name as the residing class.The default is false (it is not allowed). It is legal in Java to havemethod with the same name as a class. As long as a return type is specifiedit is a method and not a constructor which it could be easily confused as.Does not check-style the name of an overridden methods because the developerdoes not have a choice in renaming such methods.

+

Checks that method names conform to a specified pattern.

Also, checks if a method name has the same name as the residing class.The default is false (it is not allowed). It is legal in Java to havemethod with the same name as a class. As long as a return type is specifiedit is a method and not a constructor which it could be easily confused as.Does not check-style the name of an overridden methods because the developerdoes not have a choice in renaming such methods.

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.MethodTypeParameterNameCheck: Description: | -

Checks that method type parameter names conform to a format specified by the formatproperty.

+

Checks that method type parameter 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.PackageNameCheck: Description: | -

Checks that package names conform to a format specified by the format property.

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. 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.

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.ParameterNameCheck: Description: | -

Checks that method parameter names conform to a format specifiedby the format property. By using accessModifiers property it is possibleto specify different formats for methods at different visibility levels.

To validate catch parameters please useCatchParameterName.

To validate lambda parameters please useLambdaParameterName.

+

Checks that method parameter names conform to a specified pattern.By using accessModifiers property it is possibleto specify different formats for methods at different visibility levels.

To validate catch parameters please useCatchParameterName.

To validate lambda parameters please useLambdaParameterName.

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.StaticVariableNameCheck: Description: | -

Checks that {@code static}, non-{@code final} variable names conform to a formatspecified by the format property.

+

Checks that static, non-final variable namesconform 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.TypeNameCheck: Description: | -

Checks that type names for classes, interfaces, enums, and annotations conform to aformat specified by the format property.

+

Checks that type 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.regexp.RegexpCheck: Description: | -

A check that makes sure 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 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.

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.RegexpMultilineCheck: Description: | -

A check for detecting that matches across multiple lines.Works with any file type.

Rationale: This check can be used to when the regularexpression can be span multiple lines.

+

Checks that a specified pattern matches across multiple lines inany file type.

Rationale: This check can be used to when the regularexpression can be span multiple 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.regexp com.puppycrawl.tools.checkstyle.checks.regexp.RegexpOnFilenameCheck: Description: | -

Implementation of a check that looks for a file name and/or path match (or mis-match)against specified patterns. 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 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.

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: | -

A check for detecting single lines that match a suppliedregular expression. Works with 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: | -

A check for detecting single lines that match a suppliedregular expression 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 @@ -966,19 +996,19 @@ com.puppycrawl.tools.checkstyle.checks.sizes.ParameterNumberCheck: Package: com.puppycrawl.tools.checkstyle.checks.sizes com.puppycrawl.tools.checkstyle.checks.whitespace.EmptyForInitializerPadCheck: Description: | -

Checks the padding of an empty for initializer; that is whetherwhite 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--)

+

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--)

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.EmptyForIteratorPadCheck: Description: | -

Checks the padding of an empty for iterator; that is whether a whitespace is required at an empty for iterator, or such white spaces areforbidden. No check occurs if there is a line wrap at the iterator,as in


for (Iterator foo = very.long.line.iterator();
foo.hasNext();
)

+

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


for (Iterator foo = very.long.line.iterator();
foo.hasNext();
)

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.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 AST siblings,not after line where token is found.

+

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.

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 @@ -990,7 +1020,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 (">"):

Examples with correct spacing:


// Generic methods definitions
public void <K, V extends Number> boolean foo(K, V) {}
// Generic type definition
class name<T1, T2, ..., Tn> {}
// Generic type reference
OrderedPair<String, Box<Integer>> p;
// Generic preceded method name
boolean same = Util.<Integer, String>compare(p1, p2);
// Diamond operator
Pair<Integer, String> p1 = new Pair<>(1, "apple");
// Method reference
List<T> list = ImmutableList.Builder<T>::new;
// Method reference
sort(list, Comparable::<String>compareTo);

+

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 (">"):

Examples with correct spacing:


// Generic methods definitions
public void <K, V extends Number> boolean foo(K, V) {}
// Generic type definition
class name<T1, T2, ..., Tn> {}
// Generic type reference
OrderedPair<String, Box<Integer>> p;
// Generic preceded method name
boolean same = Util.<Integer, String>compare(p1, p2);
// Diamond operator
Pair<Integer, String> p1 = new Pair<>(1, "apple");
// Method reference
List<T> list = ImmutableList.Builder<T>::new;
// Method reference
sort(list, Comparable::<String>compareTo);
// Constructor call
MyClass obj = new <String>MyClass();

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 @@ -1026,7 +1056,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; i.e. 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 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.

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 @@ -1056,7 +1086,7 @@ com.puppycrawl.tools.checkstyle.checks.whitespace.WhitespaceAfterCheck: Package: com.puppycrawl.tools.checkstyle.checks.whitespace com.puppycrawl.tools.checkstyle.checks.whitespace.WhitespaceAroundCheck: Description: | -

Checks that a token is surrounded by whitespace. Empty constructor,method, class, enum, interface, loop bodies (blocks), lambdas of the form

public MyClass() {} // empty constructor
public void func() {} // empty method
public interface Foo {} // empty interface
public class Foo {} // empty class
public enum Foo {} // empty enum
MyClass c = new MyClass() {}; // empty anonymous class
while (i = 1) {} // empty while loop
for (int i = 1; i > 1; i++) {} // empty for loop
do {} while (i = 1); // empty do-while loop
Runnable noop = () -> {}; // empty lambda
public @interface Beta {} // empty annotation type

may optionally be exempted from the policy using the allowEmptyMethods, allowEmptyConstructors, allowEmptyTypes, allowEmptyLoops,allowEmptyLambdas and allowEmptyCatchesproperties.

This check does not flag as violation double brace initialization like:


new Properties() {{
setProperty("key", "value");
}};

Parameter allowEmptyCatches allows to suppress violations when tokenlist contains SLIST to check if beginning of block is surrounded bywhitespace and catch block is empty, for example:


try {
k = 5 / i;
} catch (ArithmeticException ex) {}

With this property turned off, this raises violation because the beginning of thecatch block (left curly bracket) is not separated from the end of the catchblock (right curly bracket).

+

Checks that a token is surrounded by whitespace. Empty constructor,method, class, enum, interface, loop bodies (blocks), lambdas of the form

public MyClass() {} // empty constructor
public void func() {} // empty method
public interface Foo {} // empty interface
public class Foo {} // empty class
public enum Foo {} // empty enum
MyClass c = new MyClass() {}; // empty anonymous class
while (i = 1) {} // empty while loop
for (int i = 1; i > 1; i++) {} // empty for loop
do {} while (i = 1); // empty do-while loop
Runnable noop = () -> {}; // empty lambda
public @interface Beta {} // empty annotation type

may optionally be exempted from the policy using the allowEmptyMethods, allowEmptyConstructors, allowEmptyTypes, allowEmptyLoops,allowEmptyLambdas and allowEmptyCatchesproperties.

This check does not flag as violation double brace initialization like:

new Properties() {{setProperty("key", "value");}};

Parameter allowEmptyCatches allows to suppress violations when tokenlist contains SLIST to check if beginning of block is surrounded bywhitespace and catch block is empty, for example:

try {k = 5 / i;} catch (ArithmeticException ex) {}

With this property turned off, this raises violation because the beginning of thecatch block (left curly bracket) is not separated from the end of the catchblock (right curly 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 From 0eec17ab59b48a6bab1932684295af0f8392efd6 Mon Sep 17 00:00:00 2001 From: Will Fleming Date: Fri, 6 Mar 2020 11:01:42 -0500 Subject: [PATCH 2/2] Update config for JavadocMethodo https://checkstyle.org/config_javadoc.html#JavadocMethod Available properties here seem to have changed: `validateThrows` seems to be the replacement for the two other throws-related properties that were previously here. --- config/codeclimate_checkstyle.xml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/config/codeclimate_checkstyle.xml b/config/codeclimate_checkstyle.xml index 726e41b..34bd873 100644 --- a/config/codeclimate_checkstyle.xml +++ b/config/codeclimate_checkstyle.xml @@ -127,10 +127,9 @@ - - +