From 402a50e72f6d35c1a2a495af7d10be726823bcf4 Mon Sep 17 00:00:00 2001
From: Mike Poage Checks the style of elements in annotations. Annotations have three element styles starting with the least verbose. To not enforce an element style a Using the Using the Using the The ending parenthesis are optional when using annotations with no elements.To always require ending parenthesis use the 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 By default the 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 Using the Using the Using the The ending parenthesis are optional when using annotations with no elements.To always require ending parenthesis use the 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 By default, the 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.
Verifies that the annotation 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:
+ Verifies that the annotation Both ways of flagging deprecation serve their own purpose.The @Deprecated annotation is used for compilers and development tools.The @deprecated javadoc tag is used to document why something is deprecatedand what, if any, alternatives exist. In order to properly mark something as deprecated both forms ofdeprecation should be present. Package deprecation is an exception to the rule of always using thejavadoc tag and annotation to deprecate. It is not clear if thejavadoc tool will support it or not as newer versions keep flip-floppingon if it is supported or will cause an error.See JDK-8160601.The deprecated javadoc tag is currently the only way to say why the packageis deprecated and what to use instead. Until this is resolved, if youdon't want to print violations on package-info, you can use afilter to ignore these files untilthe javadoc tool faithfully supports it. An example config usingSuppressionSingleFilter is:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Maintains a set of check suppressions from
+ Maintains a set of check suppressions from
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
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 and debugging / refactoring leftovers such as 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.
+ 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 and debugging / refactoring leftovers such as A case in a switch statement does not implicitly form a block.Thus, to be able to introduce local variables that have casescope it is necessary to open a nested block. This issupported, set the allowInSwitchCase property to true andinclude all statements of the case in the block.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Checks for empty blocks. This check does not validate sequential blocks. Sequential blocks won't be checked. Also, no violations for fallthrough: NOTE: This check processes LITERAL_CASE and LITERAL_DEFAULT separately.Verification empty block is done for single most nearest {@code case} or {@code default}.
+ Checks for empty blocks. This check does not validate sequential blocks. Sequential blocks won't be checked. Also, no violations for fallthrough: NOTE: This check processes LITERAL_CASE and LITERAL_DEFAULT separately.Verification empty block is done for single nearest {@code case} or {@code default}.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Checks for empty catch blocks.By default check allows empty catch block with any comment inside.
+ Checks for empty catch blocks.By default, check allows empty catch block with any comment inside.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Detects double brace initialization. Rationale: Double brace initialization (set ofInstance Initializers in class body) may look cool,but it is considered as anti-pattern and should be avoided.This is also can lead to a hard-to-detect memory leak, if the anonymous class instance isreturned outside and other object(s) hold reference to it.Created anonymous class is not static, it holds an implicit reference to the outer classinstance.See thisblog post andarticle for more details.Check ignores any comments and semicolons in class body.
+ Detects double brace initialization. Rationale: Double brace initialization (set ofInstance Initializers in class body) may look cool,but it is considered as anti-pattern and should be avoided.This is also can lead to a hard-to-detect memory leak, if the anonymous class instance isreturned outside and other object(s) hold reference to it.Created anonymous class is not static, it holds an implicit reference to the outer classinstance.See thisblog post andarticle for more details.Check ignores any comments and semicolons in class body.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Checks for fall-through in 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 the Note: The check assumes that there is no unreachablecode in the
+ Checks for fall-through in 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 the Note: The check assumes that there is no unreachablecode in the
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Checks for illegal tokens. By default labels are prohibited. Rationale: Certain language features can harm readability, lead toconfusion or are not obvious to novice developers. Other featuresmay be discouraged in certain frameworks, such as not havingnative methods in Enterprise JavaBeans components.
+ Checks for illegal tokens. By default, labels are prohibited. Rationale: Certain language features can harm readability, lead toconfusion or are not obvious to novice developers. Other featuresmay be discouraged in certain frameworks, such as not havingnative methods in Enterprise JavaBeans components.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Checks specified tokens text for matching an illegal pattern.By default no tokens are specified.
+ Checks specified tokens text for matching an illegal pattern.By default, no tokens are specified.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Checks for assignments in subexpressions, such as in Rationale: With the exception of loop idioms,all assignments should occur in their own top-level statementto increase readability. With inner assignments like the one given above, it is difficultto see all places where a variable is set. Note: Check allows usage of the popular assignments in loops: Assignment inside a condition is not a problem here, as the assignment is surrounded byan extra pair of parentheses. The comparison is
+ Checks for assignments in subexpressions, such as in Rationale: Except for the loop idioms,all assignments should occur in their own top-level statementto increase readability. With inner assignments like the one given above, it is difficultto see all places where a variable is set. Note: Check allows usage of the popular assignments in loops: Assignment inside a condition is not a problem here, as the assignment is surrounded byan extra pair of parentheses. The comparison is
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Evaluates Xpath query and report violation on all matching AST nodes. This check allowsuser to implement custom checks using Xpath. If Xpath query is not specified explicitly,then the check does nothing. It is recommended to define custom message for violation to explain what is not allowedand what to use instead, default message might be too abstract. To customize a messageyou need to add Please read more about Xpath syntax atXpath Syntax.Information regarding Xpath functions can be found atXSLT/XPathReference. Note, that @text attribute can used only with token types thatare listed inXpathUtil.
+ Evaluates Xpath query and report violation on all matching AST nodes. This check allowsuser to implement custom checks using Xpath. If Xpath query is not specified explicitly,then the check does nothing. It is recommended to define custom message for violation to explain what is not allowedand what to use instead, default message might be too abstract. To customize a messageyou need to add Please read more about Xpath syntax atXpath Syntax.Information regarding Xpath functions can be found atXSLT/XPathReference. Note, that @text attribute can be used only with token types thatare listed inXpathUtil.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Checks that switch statement has a Rationale: It's usually a good idea to introduce a default case inevery switch statement. Even if the developer is sure that allcurrently possible cases are covered, this should be expressed inthe default branch, e.g. by using an assertion. This way the code isprotected against later changes, e.g. introduction of new types in anenumeration type. Note that the compiler requires switch expressionsto be exhaustive, so this check does not enforce default branches onsuch expressions.
+ Checks that switch statement has a Rationale: It's usually a good idea to introduce a default case inevery switch statement. Even if the developer is sure that allcurrently possible cases are covered, this should be expressed inthe default branch, e.g. by using an assertion. This way the code isprotected against later changes, e.g. introduction of new types in anenumeration type. This check does not validate any switch expressions. Rationale:The compiler requires switch expressions to be exhaustive. This meansthat all possible inputs must be covered. This check does not validate switch statements that use pattern or nulllabels. Rationale: Switch statements that use pattern or null labels arechecked by the compiler for exhaustiveness. This means that all possibleinputs must be covered. See theJava Language Specification for more information about switch statementsand expressions.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Checks that for loop control variables are not modified insidethe for block. An example is: 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:
+ Checks that for loop control variables are not modified insidethe for block. An example is: 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: NOTE:The check works with only primitive type variables.The check will not work for arrays used as control variable.An example is
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Checks that the clone method is not overridden from theObject class. This check is almost exactly the same as the See Object.clone() Rationale: The clone method relies on strange, hard to follow rules thatare difficult to get right and do not work in all situations.In some cases, either a copy constructoror a static factory method can be used instead of the clone methodto return copies of an object.For more information on rules for the clone method and its issues, see Effective Java:Programming Language Guide First Edition by Joshua Blochpages 45-52. Below are some of the rules/reasons why the clone method should be avoided. Two alternatives to the clone method, in some cases, is a copy constructor or a staticfactory method to return copies of an object. Both of these approaches are simpler anddo not conflict with final fields. They do not force the calling client to handle aCloneNotSupportedException. They also are typed therefore no casting is necessary.Finally, they are more flexible since they can take interface types rather than concreteclasses. Sometimes a copy constructor or static factory is not an acceptable alternative to theclone method. The example below highlights the limitation of a copy constructor(or static factory). Assume Square is a subclass for Shape. ...assume at this point the code knows nothing of s1 being a Square that's the beautyof polymorphism but the code wants to copy the Square which is declared as a Shape,its super type... The working solution (without knowing about all subclasses and doing many casts) is to dothe following (assuming correct clone implementation). Just keep in mind if this type of polymorphic cloning is required then a properlyimplemented clone method may be the best choice. Much of this information was taken from Effective Java: Programming Language Guide FirstEdition by Joshua Bloch pages 45-52. Give Bloch credit for writing an excellent book.
+ Checks that the clone method is not overridden from theObject class. This check is almost exactly the same as the See Object.clone() Rationale: The clone method relies on strange, hard to follow rules thatare difficult to get right and do not work in all situations.In some cases, either a copy constructoror a static factory method can be used instead of the clone methodto return copies of an object.For more information on rules for the clone method and its issues, see Effective Java:Programming Language Guide First Edition by Joshua Blochpages 45-52. Below are some rules/reasons why the clone method should be avoided. Two alternatives to the clone method, in some cases, is a copy constructor or a staticfactory method to return copies of an object. Both of these approaches are simpler anddo not conflict with final fields. They do not force the calling client to handle aCloneNotSupportedException. They also are typed therefore no casting is necessary.Finally, they are more flexible since they can take interface types rather than concreteclasses. Sometimes a copy constructor or static factory is not an acceptable alternative to theclone method. The example below highlights the limitation of a copy constructor(or static factory). Assume Square is a subclass for Shape. ...assume at this point the code knows nothing of s1 being a Square that's the beautyof polymorphism but the code wants to copy the Square which is declared as a Shape,its super type... The working solution (without knowing about all subclasses and doing many casts) is to dothe following (assuming correct clone implementation). Just keep in mind if this type of polymorphic cloning is required then a properlyimplemented clone method may be the best choice. Much of this information was taken from Effective Java: Programming Language Guide FirstEdition by Joshua Bloch pages 45-52. Give Bloch credit for writing an excellent book.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Checks for over-complicated boolean expressions. Currently findscode like Rationale: Complex boolean logic makes code hard to understand andmaintain.
+ Checks for over-complicated boolean expressions. Currently, it findscode like Rationale: Complex boolean logic makes code hard to understand andmaintain.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Checks that string literals are not used with Rationale: Novice Java programmers often use code like: when they mean
+ Checks that string literals are not used with Rationale: Novice Java programmers often use code like: when they mean
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Checks if unnecessary parentheses are used in a statement or expression.The check will flag the following with warnings:
+ Checks if unnecessary parentheses are used in a statement or expression.The check will flag the following with warnings:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
ElementStyleOption.COMPACT_NO_ARRAY
ElementStyleOption.COMPACT
ElementStyleOption.EXPANDED
ElementStyleOption.IGNORE
type is provided.The desired style can be set through the elementStyle
property.ElementStyleOption.EXPANDED
style is more verbose.The expanded version is sometimes referred to as "named parameters" in other languages.ElementStyleOption.COMPACT
style is less verbose.This style can only be used when there is an element called 'value' which is eitherthe sole element or all other elements have default values.ElementStyleOption.COMPACT_NO_ARRAY
style is less verbose.It is similar to the ElementStyleOption.COMPACT
style but single value arraysare flagged.With annotations a single value array does not need to be placed in an array initializer.ClosingParensOption.ALWAYS
type.To never have ending parenthesis use the ClosingParensOption.NEVER
type.To not enforce a closing parenthesis preference a ClosingParensOption.IGNORE
type is provided. Set this through the closingParens
property.TrailingArrayCommaOption.ALWAYS
type.To never have a trailing comma use the TrailingArrayCommaOption.NEVER
type.To not enforce a trailing array comma preference aTrailingArrayCommaOption.IGNORE
type is provided.Set this through the trailingArrayComma
property.ElementStyleOption
is set to COMPACT_NO_ARRAY
,the TrailingArrayCommaOption
is set to NEVER
,and the ClosingParensOption
is set to NEVER
.ElementStyleOption.COMPACT_NO_ARRAY
ElementStyleOption.COMPACT
ElementStyleOption.EXPANDED
ElementStyleOption.IGNORE
type is provided.The desired style can be set through the elementStyle
property.ElementStyleOption.EXPANDED
style is more verbose.The expanded version is sometimes referred to as "named parameters" in other languages.ElementStyleOption.COMPACT
style is less verbose.This style can only be used when there is an element called 'value' which is eitherthe sole element or all other elements have default values.ElementStyleOption.COMPACT_NO_ARRAY
style is less verbose.It is similar to the ElementStyleOption.COMPACT
style but single value arraysare flagged.With annotations a single value array does not need to be placed in an array initializer.ClosingParensOption.ALWAYS
type.To never have ending parenthesis use the ClosingParensOption.NEVER
type.To not enforce a closing parenthesis preference a ClosingParensOption.IGNORE
type is provided. Set this through the closingParens
property.TrailingArrayCommaOption.ALWAYS
type.To never have a trailing comma use the TrailingArrayCommaOption.NEVER
type.To not enforce a trailing array comma preference aTrailingArrayCommaOption.IGNORE
type is provided.Set this through the trailingArrayComma
property.ElementStyleOption
is set to COMPACT_NO_ARRAY
,the TrailingArrayCommaOption
is set to NEVER
,and the ClosingParensOption
is set to NEVER
.@Deprecated
and the Javadoc tag@deprecated
are both present when either of them is present.
<!-- 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>
@Deprecated
and the Javadoc tag@deprecated
are both present when either of them is present.
<!-- required till https://bugs.openjdk.org/browse/JDK-8160601 -->
<module name="SuppressionSingleFilter">
<property name="checks" value="MissingDeprecatedCheck"/>
<property name="files" value="package-info\.java"/>
</module>
@SuppressWarnings
annotations. It allows toprevent Checkstyle from reporting violations from parts of codethat were annotated with @SuppressWarnings
andusing name of the check to be excluded. You can also definealiases for check names that need to be suppressed.@SuppressWarnings
annotations. It allows toprevent Checkstyle from reporting violations from parts of codethat were annotated with @SuppressWarnings
andusing name of the check to be excluded. It is possible to suppressall the checkstyle warnings with the argument"all"
.You can also use a checkstyle:
prefix to prevent compiler fromprocessing these annotations. You can also definealiases for check names that need to be suppressed.
public void guessTheOutput()
{
int whichIsWhich = 0;
{
whichIsWhich = 2;
}
System.out.println("value = " + whichIsWhich);
}
// if (conditionThatIsNotUsedAnyLonger)
{
System.out.println("unconditional");
}
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;
}
}
public void guessTheOutput()
{
int whichIsWhich = 0;
{
whichIsWhich = 2;
}
System.out.println("value = " + whichIsWhich);
}
// if (conditionThatIsNotUsedAnyLonger)
{
System.out.println("unconditional");
}
switch (a) {
case 1: // no violation
case 2: // no violation
case 3: someMethod(); { } // no violation
default: break;
}
switch (a) {
case 1: // no violation
case 2: // no violation
case 3: someMethod(); { } // no violation
default: break;
}
switch
statements. Finds locations where a case
contains Java code but lacks a break
, return
,throw
or continue
statement.case
triggering the warning or onthe same line before the case
(ugly, but possible).case
.switch
statements. Finds locations where a case
contains Java code but lacks a break
, return
,yield
, throw
or continue
statement.case
triggering the warning or onthe same line before the case
(ugly, but possible).case
.String s = Integer.toString(i = 2);
.
String line;
while ((line = bufferedReader.readLine()) != null) { // OK
// process the line
}
for (;(line = bufferedReader.readLine()) != null;) { // OK
// process the line
}
do {
// process the line
}
while ((line = bufferedReader.readLine()) != null); // OK
!= null
and there is nochance that intention was to write line == reader.readLine()
.String s = Integer.toString(i = 2);
.
String line;
while ((line = bufferedReader.readLine()) != null) { // OK
// process the line
}
for (;(line = bufferedReader.readLine()) != null;) { // OK
// process the line
}
do {
// process the line
}
while ((line = bufferedReader.readLine()) != null); // OK
!= null
and there is nochance that intention was to write line == reader.readLine()
.message
element with matchxpath.match askey
attribute and desired message as value
attribute.message
element with matchxpath.match askey
attribute and desired message as value
attribute.default
clause.default
clause.
for (int i = 0; i < 1; i++) {
i++; //violation
}
for (int i = 0; i < 10;) {
i++;
}
for (int i = 0; i < 1; i++) {
i++; // violation
}
for (int i = 0; i < 10;) {
i++;
}
for (int a[]={0};a[0] < 10;a[0]++) {
a[0]++; // it will skip this violation
}
NoFinalizerCheck
.
Shape s1 = new Square();
System.out.println(s1 instanceof Square); //true
Shape s2 = new Shape(s1); //using the copy constructor
System.out.println(s2 instanceof Square); //false
Shape s2 = s1.clone();
System.out.println(s2 instanceof Square); //true
NoFinalizerCheck
.
Shape s1 = new Square();
System.out.println(s1 instanceof Square); //true
Shape s2 = new Shape(s1); //using the copy constructor
System.out.println(s2 instanceof Square); //false
Shape s2 = s1.clone();
System.out.println(s2 instanceof Square); //true
if (b == true)
, b || true
, !false
,etc. if (b == true)
, b || true
, !false
,boolean a = q > 12 ? true : false
,etc.==
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.
if (x == "something")
if ("something".equals(x))
==
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.
if (x == "something")
if ("something".equals(x))
return (x); // parens around identifier
return (x + 1); // parens around return value
int x = (y / 2 + 1); // parens around assignment rhs
for (int i = (0); i < 10; i++) { // parens around literal
t -= (z + 1); // parens around assignment rhs
return (x); // parens around identifier
return (x + 1); // parens around return value
int x = (y / 2 + 1); // parens around assignment rhs
for (int i = (0); i < 10; i++) { // parens around literal
t -= (z + 1); // parens around assignment rhs
boolean a = (x > 7 && y > 5) // parens around expression
|| z < 9;
boolean b = (~a) > -27 // parens around ~a
&& (a-- < 30); // parens around expression
Checks that a local variable is declared and/or assigned, but not used.Doesn't support pattern variables yet.Doesn't check array components as arraycomponents are classified as different kind of variables by JLS.
+ This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project. +
+ Package: com.puppycrawl.tools.checkstyle.checks.coding com.puppycrawl.tools.checkstyle.checks.coding.VariableDeclarationUsageDistanceCheck: Description: | -Checks the distance between declaration of variable and its first usage.
+
Checks the distance between declaration of variable and its first usage.Note : Variable declaration/initialization statements are not countedwhile calculating length.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.coding @@ -403,13 +409,13 @@ com.puppycrawl.tools.checkstyle.checks.design.DesignForExtensionCheck: Package: com.puppycrawl.tools.checkstyle.checks.design com.puppycrawl.tools.checkstyle.checks.design.FinalClassCheck: Description: | -Checks that a class which has only private constructors is declaredas final. Doesn't check for classes nested in interfacesor annotations, as they are always final
there.
+
Checks that a class that has only private constructors andhas no descendant classes is declared as final.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.design com.puppycrawl.tools.checkstyle.checks.design.HideUtilityClassConstructorCheck: Description: | -Makes sure that utility classes (classes that contain only staticmethods or fields in their API) do not have a public constructor.
Rationale: Instantiating utility classes does not make sense. Hencethe constructors should either be private or (if you want to allowsubclassing) protected. A common mistake is forgetting to hide thedefault constructor.
If you make the constructor protected you may want to consider thefollowing constructor implementation technique to disallowinstantiating subclasses:
+
Makes sure that utility classes (classes that contain only staticmethods or fields in their API) do not have a public constructor.
Rationale: Instantiating utility classes does not make sense. Hence,the constructors should either be private or (if you want to allowsubclassing) protected. A common mistake is forgetting to hide thedefault constructor.
If you make the constructor protected you may want to consider thefollowing constructor implementation technique to disallowinstantiating subclasses:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.design @@ -427,13 +433,13 @@ com.puppycrawl.tools.checkstyle.checks.design.InterfaceIsTypeCheck: Package: com.puppycrawl.tools.checkstyle.checks.design com.puppycrawl.tools.checkstyle.checks.design.MutableExceptionCheck: Description: | -Ensures that exception classes (classes with names conforming to some regularexpression and explicitly extending classes with names conforming to otherregular expression) are immutable, that is, that they have only final fields.
The current algorithm is very simple: it checks that all members ofexception are final. The user can still mutate an exception's instance(e.g. Throwable has a method called setStackTrace
which changes the exception's stack trace). But, at least, all informationprovided by this exception type is unchangeable.
Rationale: Exception instances should represent an errorcondition. Having non final fields not only allows the state to bemodified by accident and therefore mask the original condition butalso allows developers to accidentally forget to set the initial state.In both cases, code catching the exception could draw incorrectconclusions based on the state.
+
Ensures that exception classes (classes with names conforming to some patternand explicitly extending classes with names conforming to otherpattern) are immutable, that is, that they have only final fields.
The current algorithm is very simple: it checks that all members ofexception are final. The user can still mutate an exception's instance(e.g. Throwable has a method called setStackTrace
which changes the exception's stack trace). But, at least, all informationprovided by this exception type is unchangeable.
Rationale: Exception instances should represent an errorcondition. Having non-final fields not only allows the state to bemodified by accident and therefore mask the original condition butalso allows developers to accidentally forget to set the initial state.In both cases, code catching the exception could draw incorrectconclusions based on the state.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.design com.puppycrawl.tools.checkstyle.checks.design.OneTopLevelClassCheck: Description: | -Checks that each top-level class, interface, enumor annotation resides in a source file of its own.Official description of a 'top-level' term:7.6. Top Level Type Declarations.If file doesn't contains public class, interface, enum or annotation,top-level type is the first type in file.
+
Checks that each top-level class, interface, enumor annotation resides in a source file of its own.Official description of a 'top-level' term:7.6. Top Level Type Declarations.If file doesn't contain public class, interface, enum or annotation,top-level type is the first type in file.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.design @@ -445,13 +451,13 @@ com.puppycrawl.tools.checkstyle.checks.design.ThrowsCountCheck: Package: com.puppycrawl.tools.checkstyle.checks.design com.puppycrawl.tools.checkstyle.checks.design.VisibilityModifierCheck: Description: | -Checks visibility of class members. Only static final, immutable or annotatedby specified annotation members may be public; other class members must be privateunless the property protectedAllowed
or packageAllowed
is set.
Public members are not flagged if the name matches the publicmember regular expression (contains "^serialVersionUID$"
by default).
Note thatCheckstyle 2 used to include "^f[A-Z][a-zA-Z0-9]*$"
in the defaultpattern to allow names used in container-managed persistence for Enterprise JavaBeans(EJB) 1.1 with the default settings. With EJB 2.0 it is no longer necessary to havepublic access for persistent fields, so the default has been changed.
Rationale: Enforce encapsulation.
Check also has options making it less strict:
ignoreAnnotationCanonicalNames - the list of annotations which ignore variablesin consideration. If user will provide short annotation name that type will match to anynamed the same type without consideration of package.
allowPublicFinalFields - which allows public final fields.
allowPublicImmutableFields - which allows immutable fields to be declared aspublic if defined in final class.
Field is known to be immutable if:
Classes known to be immutable are listed in immutableClassCanonicalNames by theircanonical names.
Property Rationale: Forcing all fields of class to have private modifier by default isgood in most cases, but in some cases it drawbacks in too much boilerplate get/set code.One of such cases are immutable classes.
Restriction: Check doesn't check if class is immutable, there's nochecking if accessory methods are missing and all fields are immutable, we only checkif current field is immutable or final. Under the flagallowPublicImmutableFields, the enclosing class must also be final, to encourageimmutability. Under the flag allowPublicFinalFields, the final modifier onthe enclosing class is optional.
Star imports are out of scope of this Check. So if one of type imported viastar import collides with user specified one by its short name -there won't be Check's violation.
+
Checks visibility of class members. Only static final, immutable or annotatedby specified annotation members may be public; other class members must be privateunless the property protectedAllowed
or packageAllowed
is set.
Public members are not flagged if the name matches the publicmember regular expression (contains "^serialVersionUID$"
by default).
Note thatCheckstyle 2 used to include "^f[A-Z][a-zA-Z0-9]*$"
in the defaultpattern to allow names used in container-managed persistence for Enterprise JavaBeans(EJB) 1.1 with the default settings. With EJB 2.0 it is no longer necessary to havepublic access for persistent fields, so the default has been changed.
Rationale: Enforce encapsulation.
Check also has options making it less strict:
ignoreAnnotationCanonicalNames - the list of annotations which ignore variablesin consideration. If user want to provide short annotation name that typewill match to any named the same type without consideration of package.
allowPublicFinalFields - which allows public final fields.
allowPublicImmutableFields - which allows immutable fields to be declared aspublic if defined in final class.
Field is known to be immutable if:
Classes known to be immutable are listed in immutableClassCanonicalNames by theircanonical names.
Property Rationale: Forcing all fields of class to have private modifier by default isgood in most cases, but in some cases it drawbacks in too much boilerplate get/set code.One of such cases are immutable classes.
Restriction: Check doesn't check if class is immutable, there's nochecking if accessory methods are missing and all fields are immutable, we only checkif current field is immutable or final. Under the flagallowPublicImmutableFields, the enclosing class must also be final, to encourageimmutability. Under the flag allowPublicFinalFields, the final modifier onthe enclosing class is optional.
Star imports are out of scope of this Check. So if one of type imported viastar import collides with user specified one by its short name -there won't be Check's violation.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.design com.puppycrawl.tools.checkstyle.filefilters.BeforeExecutionExclusionFileFilterCheck: Description: | -File filter BeforeExecutionExclusionFileFilter
decides which files should beexcluded from being processed by the utility.
By default Checkstyle includes all files and sub-directories in a directory to beprocessed and checked for violations. Users could have files that are in thesesub-directories that shouldn't be processed with their checkstyle configuration forvarious reasons, one of which is a valid Java file that won't pass Checkstyle's parser.When Checkstyle tries to parse a Java file and fails, it will throw anException
and halt parsing any more files for violations. An example of avalid Java file Checkstyle can't parse is JDK 9's module-info.java
.This file filter will exclude these problem files from being parsed,allowing the rest of the files to run normal and be validated.
Note: When a file is excluded from the utility, it is excluded from all Checks andno testing for violations will be performed on them.
+
File filter BeforeExecutionExclusionFileFilter
decides which files should beexcluded from being processed by the utility.
By default, Checkstyle includes all files and subdirectories in a directory to beprocessed and checked for violations. Users could have files that are in thesesubdirectories that shouldn't be processed with their checkstyle configuration forvarious reasons, one of which is a valid Java file that won't pass Checkstyle's parser.When Checkstyle tries to parse a Java file and fails, it will throw anException
and halt parsing any more files for violations. An example of avalid Java file Checkstyle can't parse is JDK 9's module-info.java
.This file filter will exclude these problem files from being parsed,allowing the rest of the files to run normal and be validated.
Note: When a file is excluded from the utility, it is excluded from all Checks andno testing for violations will be performed on them.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.filefilters @@ -481,7 +487,7 @@ com.puppycrawl.tools.checkstyle.filters.SuppressionSingleFilterCheck: Package: com.puppycrawl.tools.checkstyle.filters com.puppycrawl.tools.checkstyle.filters.SuppressionXpathFilterCheck: Description: | -Filter SuppressionXpathFilter
works asSuppressionFilter.Additionally, filter processes suppress-xpath
elements,which contains xpath-expressions. Xpath-expressionsare queries for suppressed nodes inside the AST tree.
Currently, filter does not support the following checks:
Also, the filter does not support suppressions inside javadoc reported by Javadoc checks:
Note, that support for these Checks will be available after resolving issues#5770 and#5777.
Currently, filter supports the followingxpath axes:
You can use the command line helper tool to generate xpathsuppressions based on your configuration file and input files.Seeherefor more details.
+
Filter SuppressionXpathFilter
works asSuppressionFilter.Additionally, filter processes suppress-xpath
elements,which contains xpath-expressions. Xpath-expressionsare queries for suppressed nodes inside the AST tree.
Currently, filter does not support the following checks:
Also, the filter does not support suppressions inside javadoc reported by Javadoc checks:
Note, that support for these Checks will be available after resolving issue#5770.
Currently, filter supports the followingxpath axes:
You can use the command line helper tool to generate xpathsuppressions based on your configuration file and input files.Seeherefor more details.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.filters @@ -493,7 +499,7 @@ com.puppycrawl.tools.checkstyle.filters.SuppressionXpathSingleFilterCheck: Package: com.puppycrawl.tools.checkstyle.filters com.puppycrawl.tools.checkstyle.filters.SuppressWarningsFilterCheck: Description: | -Filter SuppressWarningsFilter
uses annotation{@code SuppressWarnings} to suppress audit events.
Rationale: Same as forSuppressionCommentFilter
. In the contrary to ithere, comments are not used comments but the builtin syntax of@SuppressWarnings
. This can be perceived as amore elegant solution than using comments. Also this approachmaybe supported by various IDE.
Usage: This filter only works in conjunction with aSuppressWarningsHolder,since that check findsthe annotations in the Java files and makes them available forthe filter. Because of that, a configuration that includesthis filter must also includeSuppressWarningsHolder
as a child module of theTreeWalker
. Name of check in annotation is case-insensitiveand should be written with any dotted prefix or "Check" suffix removed.
+
Filter SuppressWarningsFilter
uses annotation@SuppressWarnings
to suppress audit events.
Rationale: Same as forSuppressionCommentFilter
. In the contrary to ithere, comments are not used comments but the builtin syntax of@SuppressWarnings
. This can be perceived as amore elegant solution than using comments. Also, this approachmaybe supported by various IDE.
Usage: This filter only works in conjunction with aSuppressWarningsHolder,since that check findsthe annotations in the Java files and makes them available forthe filter. Because of that, a configuration that includesthis filter must also includeSuppressWarningsHolder
as a child module of theTreeWalker
. Name of check in annotation is case-insensitiveand should be written with any dotted prefix or "Check" suffix removed.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.filters @@ -505,7 +511,7 @@ com.puppycrawl.tools.checkstyle.filters.SuppressWithNearbyCommentFilterCheck: Package: com.puppycrawl.tools.checkstyle.filters com.puppycrawl.tools.checkstyle.filters.SuppressWithPlainTextCommentFilterCheck: Description: | -Filter SuppressWithPlainTextCommentFilter
uses plain text to suppressaudit events. The filter can be used only to suppress audit events received fromthe checks which implement FileSetCheck interface. In other words, the checkswhich have Checker as a parent module. The filter knows nothing about AST,it treats only plain text comments and extracts the information requiredfor suppression from the plain text comments. Currently the filter supportsonly single line comments.
Please, be aware of the fact that, it is not recommended to use the filterfor Java code anymore, however you still are able to use it to suppress auditevents received from the checks which implement FileSetCheck interface.
Rationale: Sometimes there are legitimate reasons for violatinga check. When this is a matter of the code in question and notpersonal preference, the best place to override the policy is inthe code itself. Semi-structured comments can be associatedwith the check. This is sometimes superior to a separatesuppressions file, which must be kept up-to-date as the sourcefile is edited.
Note that the suppression comment should be put before the violation.You can use more than one suppression comment each on separate line.
+
Filter SuppressWithPlainTextCommentFilter
uses plain text to suppressaudit events. The filter can be used only to suppress audit events received fromthe checks which implement FileSetCheck interface. In other words, the checkswhich have Checker as a parent module. The filter knows nothing about AST,it treats only plain text comments and extracts the information requiredfor suppression from the plain text comments. Currently, the filter supportsonly single-line comments.
Please, be aware of the fact that, it is not recommended to use the filterfor Java code anymore, however you still are able to use it to suppress auditevents received from the checks which implement FileSetCheck interface.
Rationale: Sometimes there are legitimate reasons for violatinga check. When this is a matter of the code in question and notpersonal preference, the best place to override the policy is inthe code itself. Semi-structured comments can be associatedwith the check. This is sometimes superior to a separatesuppressions file, which must be kept up-to-date as the sourcefile is edited.
Note that the suppression comment should be put before the violation.You can use more than one suppression comment each on separate line.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.filters @@ -517,7 +523,7 @@ com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck: Package: com.puppycrawl.tools.checkstyle.checks.header com.puppycrawl.tools.checkstyle.checks.header.RegexpHeaderCheck: Description: | -Checks the header of a source file against a header that contains aregular expression for each line of the source header.
Rationale: In some projects checking against afixed header is not sufficient, e.g. the header might require acopyright line where the year information is not static.
For example, consider the following header:
Lines 1 and 6 demonstrate a more compact notation for 71 '/'characters. Line 4 enforces that the copyright notice includes afour digit year. Line 5 is an example how to enforce revisioncontrol keywords in a file header. Lines 12-14 is a template forjavadoc (line 13 is so complicated to remove conflict with and ofjavadoc comment). Lines 7, 9 and 11 will be treated as '^$' andwill forcefully expect the line to be empty.
Different programming languages have different comment syntaxrules, but all of them start a comment with a non-wordcharacter. Hence you can often use the non-word characterclass to abstract away the concrete comment syntax and allowchecking the header for different languages with a singleheader definition. For example, consider the following headerspecification (note that this is not the full Apache licenseheader):
Lines 1 and 2 leave room for technical header lines, e.g. the"#!/bin/sh" line in Unix shell scripts, or the XML file headerof XML files. Set the multiline property to "1, 2" so theselines can be ignored for file types where they do no apply.Lines 3 through 6 define the actual header content. Note howlines 2, 4 and 5 use escapes for characters that have specialregexp semantics.
In default configuration, if header is not specified, the default valueof header is set to null and the check does not rise any violations.
+
Checks the header of a source file against a header that contains apattern for each line of the source header.
Rationale: In some projects checking against afixed header is not sufficient, e.g. the header might require acopyright line where the year information is not static.
For example, consider the following header:
Lines 1 and 6 demonstrate a more compact notation for 71 '/'characters. Line 4 enforces that the copyright notice includes afour digit year. Line 5 is an example how to enforce revisioncontrol keywords in a file header. Lines 12-14 is a template forjavadoc (line 13 is so complicated to remove conflict with and ofjavadoc comment). Lines 7, 9 and 11 will be treated as '^$' andwill forcefully expect the line to be empty.
Different programming languages have different comment syntaxrules, but all of them start a comment with a non-wordcharacter. Hence, you can often use the non-word characterclass to abstract away the concrete comment syntax and allowchecking the header for different languages with a singleheader definition. For example, consider the following headerspecification (note that this is not the full Apache licenseheader):
Lines 1 and 2 leave room for technical header lines, e.g. the"#!/bin/sh" line in Unix shell scripts, or the XML file headerof XML files. Set the multiline property to "1, 2" so theselines can be ignored for file types where they do no apply.Lines 3 through 6 define the actual header content. Note howlines 2, 4 and 5 use escapes for characters that have specialregexp semantics.
In default configuration, if header is not specified, the default valueof header is set to null and the check does not rise any violations.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.header @@ -547,13 +553,13 @@ com.puppycrawl.tools.checkstyle.checks.imports.IllegalImportCheck: Package: com.puppycrawl.tools.checkstyle.checks.imports com.puppycrawl.tools.checkstyle.checks.imports.ImportControlCheck: Description: | -Controls what can be imported in each package and file. Useful forensuring that application layering rules are not violated,especially on large projects.
You can control imports based on the a package name or based on the filename. When controlling packages, all files and sub-packages in the declaredpackage will be controlled by this check. To specify differences between a main packageand a sub-package, you must define the sub-package inside the main package. Whencontrolling file, only the file name is considered and only files processed byTreeWalker. The file's extension is ignored.
Short description of the behaviour:
The DTD for a import control XML document is at https://checkstyle.org/dtds/import_control_1_4.dtd. Itcontains documentation on each of the elements and attributes.
The check validates a XML document when it loads the document.To validate against the above DTD, include the followingdocument type declaration in your XML document:
<!DOCTYPE import-control PUBLIC"-//Checkstyle//DTD ImportControl Configuration 1.4//EN""https://checkstyle.org/dtds/import_control_1_4.dtd">
+
Controls what can be imported in each package and file. Useful forensuring that application layering rules are not violated,especially on large projects.
You can control imports based on the package name or based on the filename. When controlling packages, all files and sub-packages in the declaredpackage will be controlled by this check. To specify differences between a main packageand a sub-package, you must define the sub-package inside the main package. Whencontrolling file, only the file name is considered and only files processed byTreeWalker. The file's extension is ignored.
Short description of the behaviour:
The DTD for an import control XML document is at https://checkstyle.org/dtds/import_control_1_4.dtd. Itcontains documentation on each of the elements and attributes.
The check validates a XML document when it loads the document.To validate against the above DTD, include the followingdocument type declaration in your XML document:
<!DOCTYPE import-control PUBLIC"-//Checkstyle//DTD ImportControl Configuration 1.4//EN""https://checkstyle.org/dtds/import_control_1_4.dtd">
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.imports com.puppycrawl.tools.checkstyle.checks.imports.ImportOrderCheck: Description: | -Checks the ordering/grouping of imports. Features are:
+
Checks the ordering/grouping of imports. Features are:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.imports @@ -565,7 +571,7 @@ com.puppycrawl.tools.checkstyle.checks.imports.RedundantImportCheck: Package: com.puppycrawl.tools.checkstyle.checks.imports com.puppycrawl.tools.checkstyle.checks.imports.UnusedImportsCheck: Description: | -Checks for unused import statements. Checkstyle uses a simple butvery reliable algorithm to report on unused import statements. Animport statement is considered unused if:
importjava.io.*;
. Most IDE's provide very sophisticated checksfor imports that handle wild-card imports.java.lang
package. For example importing java.lang.String
.java.util.List
would beconsidered referenced with the Javadoc comment{@link List}
. The alternative to avoid introducing acompile time dependency would be to write the Javadoc comment as{@link java.util.List}
.The main limitation of this check is handling the case wherean imported type has the same name as a declaration, such as amember variable.
For example, in the following case the import java.awt.Component
will not be flagged as unused:
+
Checks for unused import statements. Checkstyle uses a simple butvery reliable algorithm to report on unused import statements. Animport statement is considered unused if:
importjava.io.*;
. Most IDE's provide very sophisticated checksfor imports that handle wild-card imports.java.lang
package. For example importing java.lang.String
.java.util.List
would beconsidered referenced with the Javadoc comment{@link List}
. The alternative to avoid introducing acompile-time dependency would be to write the Javadoc comment as{@link java.util.List}
.The main limitation of this check is handling the cases where:
For example, in the following case all imports will not be flagged as unused:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.imports @@ -595,7 +601,7 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocContentLocationCheck: Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck: Description: | -Checks the Javadoc of a method or constructor. The scopeto verify is specified using the Scope
class anddefaults to Scope.PRIVATE
. To verify anotherscope, set property scope to a differentscope.
Violates parameters and type parametersfor which no param tags arepresent can be suppressed by defining propertyallowMissingParamTags
.
Violates methods which return non-void but for which no return tag ispresent can be suppressed by defining propertyallowMissingReturnTag
.
Violates exceptions which are declared to be thrown (by throws
in the methodsignature or by throw new
in the method body), but for which no throws tag ispresent by activation of property validateThrows
.Note that throw new
is not checked in the following places:
ATTENTION: Checkstyle does not have information about hierarchy of exception typesso usage of base class is considered as separate exception type.As workaround you need to specify both types in javadoc (parent and exact type).
Javadoc is not required on a method that is tagged with the@Override
annotation. However underJava 5 it is not possible to mark a method required for aninterface (this was corrected under Java 6). HenceCheckstyle supports using the convention of using a single{@inheritDoc}
tag instead of all theother tags.
Note that only inheritable items will allow the{@inheritDoc}
tag to be used in placeof comments. Static methods at all visibilities, private non-staticmethods and constructors are not inheritable.
For example, if the following method isimplementing a method required by an interface, then theJavadoc could be done as:
+
Checks the Javadoc of a method or constructor.
Violates parameters and type parametersfor which no param tags arepresent can be suppressed by defining propertyallowMissingParamTags
.
Violates methods which return non-void but for which no return tag ispresent can be suppressed by defining propertyallowMissingReturnTag
.
Violates exceptions which are declared to be thrown (by throws
in the methodsignature or by throw new
in the method body), but for which no throws tag ispresent by activation of property validateThrows
.Note that throw new
is not checked in the following places:
ATTENTION: Checkstyle does not have information about hierarchy of exception typesso usage of base class is considered as separate exception type.As workaround, you need to specify both types in javadoc (parent and exact type).
Javadoc is not required on a method that is tagged with the@Override
annotation. However, underJava 5 it is not possible to mark a method required for aninterface (this was corrected under Java 6). Hence,Checkstyle supports using the convention of using a single{@inheritDoc}
tag instead of all theother tags.
Note that only inheritable items will allow the{@inheritDoc}
tag to be used in placeof comments. Static methods at all visibilities, private non-staticmethods and constructors are not inheritable.
For example, if the following method isimplementing a method required by an interface, then theJavadoc could be done as:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.javadoc @@ -613,7 +619,7 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMissingWhitespaceAfterAste Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocPackageCheck: Description: | -Checks that each Java package has a Javadoc file used forcommenting. By default it only allows a package-info.java
file, but can beconfigured to allow a package.html
file.
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.html
file.
A violation will be reported if both files exist as this is notallowed by the Javadoc tool.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.javadoc @@ -625,7 +631,7 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocParagraphCheck: Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocStyleCheck: Description: | -Validates Javadoc comments to help ensure they are well formed.
The following checks are performed:
{@inheritDoc}
tag are exempt from thisrequirement.@param
and @return
.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:
{@inheritDoc}
tag are exempt from thisrequirement.@param
and @return
.These checks were patterned after the checks made by the DocCheckdoclet available from Sun. Note: Original Sun's DocCheck tool does not exist anymore.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.javadoc @@ -637,7 +643,7 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTagContinuationIndentation Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTypeCheck: Description: | -Checks the Javadoc comments for type definitions.By default, does not check for author or version tags. Thescope to verify is specified using the Scope
class and defaults to Scope.PRIVATE
. To verifyanother scope, set property scope to one of theScope
constants. To define the format for anauthor tag or a version tag, set property authorFormat orversionFormat respectively to aregular expression.
Does not perform checks for author and version tags for innerclasses, as they should be redundant because of outer class.
Error messages about type parameters and record components for which noparam tags are present can be suppressed by defining propertyallowMissingParamTags
.
+
Checks the Javadoc comments for type definitions.By default, does not check for author or version tags. Thescope to verify is specified using the Scope
class and defaults to Scope.PRIVATE
. To verifyanother scope, set property scope to one of theScope
constants. To define the format for anauthor tag or a version tag, set property authorFormat orversionFormat respectively to apattern.
Does not perform checks for author and version tags for innerclasses, as they should be redundant because of outer class.
Error messages about type parameters and record components for which noparam tags are present can be suppressed by defining propertyallowMissingParamTags
.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.javadoc @@ -649,13 +655,13 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocVariableCheck: Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.MissingJavadocMethodCheck: Description: | -Checks for missing Javadoc comments for a method or constructor.The scope to verify is specified using the Scope
class anddefaults to Scope.PUBLIC
. To verify anotherscope, set property scope to a differentscope.
Javadoc is not required on a method that is tagged with the@Override
annotation. However underJava 5 it is not possible to mark a method required for aninterface (this was corrected under Java 6). HenceCheckstyle supports using the convention of using a single{@inheritDoc}
tag instead of all theother tags.
For getters and setters for the property allowMissingPropertyJavadoc
,the methods must match exactly the structures below.
public void setNumber(final int number){mNumber = number;}public int getNumber(){return mNumber;}public boolean isSomething(){return false;}
+
Checks for missing Javadoc comments for a method or constructor.The scope to verify is specified using the Scope
class anddefaults to Scope.PUBLIC
. To verify anotherscope, set property scope to a differentscope.
Javadoc is not required on a method that is tagged with the@Override
annotation. However, underJava 5 it is not possible to mark a method required for aninterface (this was corrected under Java 6). Hence,Checkstyle supports using the convention of using a single{@inheritDoc}
tag instead of all theother tags.
For getters and setters for the property allowMissingPropertyJavadoc
,the methods must match exactly the structures below.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.MissingJavadocPackageCheck: Description: | -Checks for missing Javadoc comments in package-info.java files.
Rationale: description and other related documentation for a package can be written upin the package-info.java file and it gets used in the production of the Javadocs.See link for more info.
+
Checks for missing package definition Javadoc comments in package-info.java files.
Rationale: description and other related documentation for a package can be written upin the package-info.java file and it gets used in the production of the Javadocs.See link for more info.
This check specifically only validates package definitions. It will not validate anymethods or interfaces declared in the package-info.java file.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.javadoc @@ -679,13 +685,13 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.RequireEmptyLineBeforeBlockTagGro Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.SingleLineJavadocCheck: Description: | -Checks that a Javadoc block can fit in a single line and doesn'tcontain block tags. Javadoc comment that contains at least one block tagshould be formatted in a few lines.
+
Checks that a Javadoc block can fit in a single-line and doesn'tcontain block tags. Javadoc comment that contains at least one block tagshould be formatted in a few lines.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.SummaryJavadocCheck: Description: | -Checks thatJavadoc summary sentence does not contain phrases that are not recommended to use.Summaries that contain only the {@inheritDoc}
tag are skipped. Check alsoviolate Javadoc that does not contain first sentence.
+
Checks thatJavadoc summary sentence does not contain phrases that are not recommended to use.Summaries that contain only the {@inheritDoc}
tag are skipped. Summariesthat contain a non-empty {@code {@return}} are allowed. Check also violate Javadoc thatdoes not contain first sentence, though with {@code {@return}} a period is not requiredas the Javadoc tool adds it.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.javadoc @@ -697,25 +703,25 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.WriteTagCheck: Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.metrics.BooleanExpressionComplexityCheck: Description: | -Restricts the number of boolean operators (&&
, ||
,&
, |
and ^
) in an expression.
Rationale: Too many conditions leads to code that is difficultto read and hence debug and maintain.
Note that the operators &
and|
are not only integer bitwise operators, they are also thenon-shortcut versions of the boolean operators&&
and ||
.
Note that &
, |
and ^
are not checkedif they are part of constructor or method callbecause they can be applied to non boolean variables andCheckstyle does not know types of methods from different classes.
+
Restricts the number of boolean operators (&&
, ||
,&
, |
and ^
) in an expression.
Rationale: Too many conditions leads to code that is difficultto read and hence debug and maintain.
Note that the operators &
and|
are not only integer bitwise operators, they are also thenon-shortcut versions of the boolean operators&&
and ||
.
Note that &
, |
and ^
are not checkedif they are part of constructor or method callbecause they can be applied to non-boolean variables andCheckstyle does not know types of methods from different classes.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.metrics com.puppycrawl.tools.checkstyle.checks.metrics.ClassDataAbstractionCouplingCheck: Description: | -Measures the number of instantiations of otherclasses within the given class or record. This type of coupling is notcaused by inheritance or the object orientedparadigm. Generally speaking, any data type with other datatypes as members or local variable that is an instantiation(object) of another class has data abstraction coupling (DAC).The higher the DAC, the more complex the structure of the class.
This check processes files in the following way:
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.excludedClasses
parameter,the class does not increase complexity.+
Measures the number of instantiations of otherclasses within the given class or record. This type of coupling is notcaused by inheritance or the object-orientedparadigm. Generally speaking, any data type with other datatypes as members or local variable that is an instantiation(object) of another class has data abstraction coupling (DAC).The higher the DAC, the more complex the structure of the class.
This check processes files in the following way:
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.excludedClasses
parameter,the class does not increase complexity.This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.metrics com.puppycrawl.tools.checkstyle.checks.metrics.ClassFanOutComplexityCheck: Description: | -Checks the number of other types a given class/record/interface/enum/annotationrelies on. Also the square of this has been shown to indicate the amount ofmaintenance required in functional programs (on a file basis) at least.
This check processes files in the following way:
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.excludedClasses
parameter,the class does not increase complexity.+
Checks the number of other types a given class/record/interface/enum/annotationrelies on. Also, the square of this has been shown to indicate the amount ofmaintenance required in functional programs (on a file basis) at least.
This check processes files in the following way:
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.excludedClasses
parameter,the class does not increase complexity.This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.metrics com.puppycrawl.tools.checkstyle.checks.metrics.CyclomaticComplexityCheck: Description: | -Checks cyclomatic complexity against a specified limit.It is a measure of the minimum number ofpossible paths through the source and therefore the number ofrequired tests, it is not a about quality of code!It is only applied to methods, c-tors,static initializers and instance initializers.
The complexity is equal to the number of decision points + 1
.Decision points: if
, while
, do
, for
, ?:
, catch
, switch
, case
statements and operators &&
and ||
in the body of target.
By pure theory level 1-4 is considered easy to test, 5-7 OK, 8-10consider re-factoring to ease testing, and 11+ re-factor now as testing will be painful.
When it comes to code quality measurement by this metriclevel 10 is very good level as a ultimate target (that is hard to archive).Do not be ashamed to have complexity level 15 or even higher,but keep it below 20 to catch really bad designed code automatically.
Please use Suppression to avoid violations on cases that could not be split in fewmethods without damaging readability of code or encapsulation.
+
Checks cyclomatic complexity against a specified limit.It is a measure of the minimum number ofpossible paths through the source and therefore the number ofrequired tests, it is not about quality of code!It is only applied to methods, c-tors,static initializers and instance initializers.
The complexity is equal to the number of decision points + 1
.Decision points: if
, while
, do
, for
, ?:
, catch
, switch
, case
statements and operators &&
and ||
in the body of target.
By pure theory level 1-4 is considered easy to test, 5-7 OK, 8-10consider re-factoring to ease testing, and 11+ re-factor now as testing will be painful.
When it comes to code quality measurement by this metriclevel 10 is very good level as a ultimate target (that is hard to archive).Do not be ashamed to have complexity level 15 or even higher,but keep it below 20 to catch really bad-designed code automatically.
Please use Suppression to avoid violations on cases that could not be split in fewmethods without damaging readability of code or encapsulation.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.metrics @@ -727,13 +733,13 @@ com.puppycrawl.tools.checkstyle.checks.metrics.JavaNCSSCheck: Package: com.puppycrawl.tools.checkstyle.checks.metrics com.puppycrawl.tools.checkstyle.checks.metrics.NPathComplexityCheck: Description: | -Checks the NPATH complexity against a specified limit.
The NPATH metric computes the number of possible executionpaths through a function(method). It takes into account the nesting ofconditional statements and multi-part boolean expressions(A && B, C || D, E ? F :G and their combinations).
The NPATH metric was designed base on Cyclomatic complexity toavoid problem of Cyclomatic complexity metric like nesting level within afunction(method).
Metric was described at "NPATH: a measure of execution pathcomplexity and its applications".If you need detailed description of algorithm, please read that article,it is well written and have number of examples and details.
Here is some quotes:
An NPATH threshold value of 200 has been establishedfor a function. The value 200 is based on studies doneat AT&T Bell Laboratories [1988 year].
Some of the most effective methods of reducing the NPATH value include:
- distributing functionality;
- implementing multiple if statements as a switch statement;
- creating a separate function for logical expressions with a highcount of variables and (&&) and or (||) operators.
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.
Structure | Complexity expression |
---|---|
if ([expr]) { [if-range] } | NP(if-range) + 1 + NP(expr) |
if ([expr]) { [if-range] } else { [else-range] } | NP(if-range)+ NP(else-range) + NP(expr) |
while ([expr]) { [while-range] } | NP(while-range) + NP(expr) + 1 |
do { [do-range] } while ([expr]) | NP(do-range) + NP(expr) + 1 |
for([expr1]; [expr2]; [expr3]) { [for-range] } | NP(for-range) + NP(expr1)+ NP(expr2) + NP(expr3) + 1 |
switch ([expr]) { case : [case-range] default: [default-range] } | S(i=1:i=n)NP(case-range[i]) + NP(default-range) + NP(expr) |
[expr1] ? [expr2] : [expr3] | NP(expr1) + NP(expr2) + NP(expr3) + 2 |
goto label | 1 |
break | 1 |
Expressions | Number of && and || operators in expression. Nooperators - 0 |
continue | 1 |
return | 1 |
Statement (even sequential statements) | 1 |
Empty block {} | 1 |
Function call | 1 |
Function(Method) declaration or Block | P(i=1:i=N)NP(Statement[i]) |
Rationale: Nejmeh says that his group had an informal NPATHlimit of 200 on individual routines; functions(methods) that exceededthis value were candidates for further decomposition - or atleast a closer look.Please do not be fanatic with limit 200- choose number that suites your project style. Limit 200 isempirical number base on some sources of at AT&T Bell Laboratoriesof 1988 year.
+
Checks the NPATH complexity against a specified limit.
The NPATH metric computes the number of possible executionpaths through a function(method). It takes into account the nesting ofconditional statements and multipart boolean expressions(A && B, C || D, E ? F :G and their combinations).
The NPATH metric was designed base on Cyclomatic complexity toavoid problem of Cyclomatic complexity metric like nesting level within afunction(method).
Metric was described at "NPATH: a measure of execution pathcomplexity and its applications".If you need detailed description of algorithm, please read that article,it is well written and have number of examples and details.
Here is some quotes:
An NPATH threshold value of 200 has been establishedfor a function. The value 200 is based on studies doneat AT&T Bell Laboratories [1988 year].
Some of the most effective methods of reducing the NPATH value include:
- distributing functionality;
- implementing multiple if statements as a switch statement;
- creating a separate function for logical expressions with a highcount of variables and (&&) and or (||) operators.
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.
Structure | Complexity expression |
---|---|
if ([expr]) { [if-range] } | NP(if-range) + 1 + NP(expr) |
if ([expr]) { [if-range] } else { [else-range] } | NP(if-range)+ NP(else-range) + NP(expr) |
while ([expr]) { [while-range] } | NP(while-range) + NP(expr) + 1 |
do { [do-range] } while ([expr]) | NP(do-range) + NP(expr) + 1 |
for([expr1]; [expr2]; [expr3]) { [for-range] } | NP(for-range) + NP(expr1)+ NP(expr2) + NP(expr3) + 1 |
switch ([expr]) { case : [case-range] default: [default-range] } | S(i=1:i=n)NP(case-range[i]) + NP(default-range) + NP(expr) |
[expr1] ? [expr2] : [expr3] | NP(expr1) + NP(expr2) + NP(expr3) + 2 |
goto label | 1 |
break | 1 |
Expressions | Number of && and || operators in expression. Nooperators - 0 |
continue | 1 |
return | 1 |
Statement (even sequential statements) | 1 |
Empty block {} | 1 |
Function call | 1 |
Function(Method) declaration or Block | P(i=1:i=N)NP(Statement[i]) |
Rationale: Nejmeh says that his group had an informal NPATHlimit of 200 on individual routines; functions(methods) that exceededthis value were candidates for further decomposition - or atleast a closer look.Please do not be fanatic with limit 200- choose number that suites your project style. Limit 200 isempirical number base on some sources of at AT&T Bell Laboratoriesof 1988 year.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.metrics com.puppycrawl.tools.checkstyle.checks.ArrayTypeStyleCheck: Description: | -Checks the style of array type definitions. Some like Java style:public static void main(String[] args)
and some likeC style: public static void main(String args[])
.
By default the Check enforces Java style.
This check strictly enforces only Java style for method return typesregardless of the value for 'javaStyle'. For example, byte[] getData()
.This is because C doesn't compile methods with array declarations on the name.
+
Checks the style of array type definitions. Some like Java style:public static void main(String[] args)
and some likeC style: public static void main(String args[])
.
By default, the Check enforces Java style.
This check strictly enforces only Java style for method return typesregardless of the value for 'javaStyle'. For example, byte[] getData()
.This is because C doesn't compile methods with array declarations on the name.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks @@ -745,13 +751,13 @@ com.puppycrawl.tools.checkstyle.checks.AvoidEscapedUnicodeCharactersCheck: Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.indentation.CommentsIndentationCheck: Description: | -Controls the indentation between comments and surrounding code.Comments are indented at the same level as the surrounding code.Detailed info about such convention can be foundhere
Please take a look at the following examples to understand how the check works:
Example #1: Block comments.
Example #2: Comment is placed at the end of the block and has previous statement.
Example #3: Comment is used as a single line border to separate groups of methods.
Example #4: Comment has distributed previous statement.
Example #5: Single line block comment is placed within an empty code block.Note, if comment is placed at the end of the empty code block, we have Checkstyle'slimitations to clearly detect user intention of explanation target - above or below. Theonly case we can assume as a violation is when a single line comment within the emptycode block has indentation level that is lower than the indentation level of the closingright curly brace.
Example #6: 'fallthrough' comments and similar.
Example #7: Comment is placed within a distributed statement.
Example #8: Comment is placed within an empty case block.Note, if comment is placed at the end of the empty case block, we have Checkstyle'slimitations to clearly detect user intention of explanation target - above or below. Theonly case we can assume as a violation is when a single line comment within the empty caseblock has indentation level that is lower than the indentation level of the next casetoken.
Example #9: Single line block comment has previous and next statement.
Example #10: Comment within the block tries to describe the next code block.
+
Controls the indentation between comments and surrounding code.Comments are indented at the same level as the surrounding code.Detailed info about such convention can be foundhere
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.indentation com.puppycrawl.tools.checkstyle.checks.DescendantTokenCheck: Description: | -Checks for restricted tokens beneath other tokens.
WARNING: This is a very powerful and flexible check, but, at thesame time, it is low-level and very implementation-dependent becauseits results depend on the grammar we use to build abstract syntaxtrees. Thus we recommend using other checks when they provide thedesired functionality. Essentially, this check just works on the levelof an abstract syntax tree and knows nothing about language structures.
+
Checks for restricted tokens beneath other tokens.
WARNING: This is a very powerful and flexible check, but, at thesame time, it is low-level and very implementation-dependent becauseits results depend on the grammar we use to build abstract syntaxtrees. Thus, we recommend using other checks when they provide thedesired functionality. Essentially, this check just works on the levelof an abstract syntax tree and knows nothing about language structures.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks @@ -769,19 +775,19 @@ com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck: Package: com.puppycrawl.tools.checkstyle.checks.indentation com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheck: Description: | -Checks whether files end with a line separator.
Rationale: Any source files and text files in general shouldend with a line separator to let other easily add new contentat the end of file and "diff" command does not show previous lines as changed.
Example (line 36 should not be in diff):
It can also trick the VCS to report the wrong owner for such lines.An engineer who has added nothing but a newline character becomesthe last known author for the entire line. As a result, a mate can askhim a question to which he will not give the correct answer.
Old Rationale: CVS source control managementsystems will even print a warning when itencounters a file that doesn't end with a line separator.
Attention: property fileExtensions works with files that are passed by similar propertyfor at Checker.Please make sure required file extensions are mentioned at Checker's fileExtensionsproperty.
+
Checks whether files end with a line separator.
Rationale: Any source files and text files in general shouldend with a line separator to let other easily add new contentat the end of file and "diff" command does not show previous lines as changed.
Example (the line with 'No newline at end of file' should not be in the diff):
It can also trick the VCS to report the wrong owner for such lines.An engineer who has added nothing but a newline character becomesthe last known author for the entire line. As a result, a mate can askhim a question to which he will not give the correct answer.
Old Rationale: CVS source control managementsystems will even print a warning when itencounters a file that doesn't end with a line separator.
Attention: property fileExtensions works with files that are passed by similar propertyfor at Checker.Please make sure required file extensions are mentioned at Checker's fileExtensionsproperty.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.NoCodeInFileCheck: Description: | -Checks whether file contains code.Files which are considered to have no code:
+
Checks whether file contains code.Files which are considered to have no code:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.OrderedPropertiesCheck: Description: | -Detects if keys in properties files are in correct order.
Rationale: Sorted properties make it easy for people to find required properties by namein file. It makes merges more easy. While there are no problems at runtime.This check is valuable only on files with string resources where order of linesdoes not matter at all, but this can be improved.E.g.: checkstyle/src/main/resources/com/puppycrawl/tools/checkstyle/messages.propertiesYou may suppress warnings of this check for files that have an logical structure likebuild files or log4j configuration files. See SuppressionFilter.<suppress checks="OrderedProperties"files="log4j.properties|ResourceBundle/Bug.*.properties|logging.properties"/>
Known limitation: The key should not contain a newline.The string compare will work, but not the line number reporting.
+
Detects if keys in properties files are in correct order.
Rationale: Sorted properties make it easy for people to find required properties by namein file. This makes it easier to merge. While there are no problems at runtime.This check is valuable only on files with string resources where order of linesdoes not matter at all, but this can be improved.E.g.: checkstyle/src/main/resources/com/puppycrawl/tools/checkstyle/messages.propertiesYou may suppress warnings of this check for files that have a logical structure likebuild files or log4j configuration files. See SuppressionFilter.<suppress checks="OrderedProperties"files="log4j.properties|ResourceBundle/Bug.*.properties|logging.properties"/>
Known limitation: The key should not contain a newline.The string compare will work, but not the line number reporting.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks @@ -793,13 +799,13 @@ com.puppycrawl.tools.checkstyle.checks.OuterTypeFilenameCheck: Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.TodoCommentCheck: Description: | -Checks for TODO:
comments. Actuallyit is a genericregularexpression matcher on Java comments. To check for otherpatterns in Java comments, set the format
property.
+
Checks for TODO:
comments. Actuallyit is a genericpattern matcher on Java comments. To check for otherpatterns in Java comments, set the format
property.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.TrailingCommentCheck: Description: | -The check to ensure that requires that comments be the only thing ona line. For the case of //
comments that means that the only thingthat should precede it is whitespace. It doesn't check comments ifthey do not end a line; for example, it accepts the following:Thread.sleep( 10 /*some comment here*/ );
Formatproperty is intended to deal with the } // while
example.
Rationale: Steve McConnell in Code Complete suggests thatendline comments are a bad practice. An end line comment would beone that is on the same line as actual code. For example:
Quoting Code Complete for the justification:
McConnell's comments on being hard to maintain when the size of the linechanges are even more important in the age of automatedrefactorings.
+
The check to ensure that lines with code do not end with comment.For the case of //
comments that means that the only thingthat should precede it is whitespace. It doesn't check comments ifthey do not end a line; for example, it accepts the following:Thread.sleep( 10 /*some comment here*/ );
Formatproperty is intended to deal with the } // while
example.
Rationale: Steve McConnell in Code Complete suggests thatendline comments are a bad practice. An end line comment would beone that is on the same line as actual code. For example:
Quoting Code Complete for the justification:
McConnell's comments on being hard to maintain when the size of the linechanges are even more important in the age of automatedrefactorings.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks @@ -811,7 +817,7 @@ com.puppycrawl.tools.checkstyle.checks.TranslationCheck: Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.UncommentedMainCheck: Description: | -Detects uncommented main
methods.
Rationale: A main
method is often used for debuggingpurposes. When debugging is finished, developers often forgetto remove the method, which changes the API and increases thesize of the resulting class or JAR file. With the exception ofthe real program entry points, all main
methods should beremoved or commented out of the sources.
+
Detects uncommented main
methods.
Rationale: A main
method is often used for debuggingpurposes. When debugging is finished, developers often forgetto remove the method, which changes the API and increases thesize of the resulting class or JAR file. Except forthe real program entry points, all main
methods should beremoved or commented out of the sources.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks @@ -841,26 +847,26 @@ com.puppycrawl.tools.checkstyle.checks.modifier.InterfaceMemberImpliedModifierCh Package: com.puppycrawl.tools.checkstyle.checks.modifier com.puppycrawl.tools.checkstyle.checks.modifier.ModifierOrderCheck: Description: | -Checks that the order of modifiers conforms to the suggestions inthe JavaLanguage specification, § 8.1.1, 8.3.1, 8.4.3 and9.4. The correct order is:
public
protected
private
abstract
default
static
final
transient
volatile
synchronized
native
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:
public
protected
private
abstract
default
static
sealed
non-sealed
final
transient
volatile
synchronized
native
strictfp
In additional, modifiers are checked to ensure all annotations aredeclared before all other modifiers.
Rationale: Code is easier to read if everybody follows a standard.
ATTENTION: We skiptype annotations from validation.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.modifier com.puppycrawl.tools.checkstyle.checks.modifier.RedundantModifierCheck: Description: | -Checks for redundant modifiers.
Rationale: The Java Language Specification stronglydiscourages the usage of public
and abstract
for methoddeclarations in interface definitions as a matter of style.
The check validates:
interface
declarations that are declaredas static
.enum
definitions that are declaredas static
.Interfaces by definition are abstract so the abstract
modifier on the interface is redundant.
Classes inside of interfaces by definition are public and static,so the public
and static
modifierson the inner classes are redundant. On the other hand, classesinside of interfaces can be abstract or non abstract.So, abstract
modifier is allowed.
Fields in interfaces and annotations are automaticallypublic, static and final, so these modifiers are redundant aswell.
As annotations are a form of interface, their fields are alsoautomatically public, static and final just as theirannotation fields are automatically public and abstract.
Enums by definition are static implicit subclasses of java.lang.Enum<E>.So, the static
modifier on the enums is redundant. In addition,if enum is inside of interface, public
modifier is also redundant.
Enums can also contain abstract methods and methods which can be overridden by thedeclared enumeration fields.See the following example:
Since these methods can be overridden in these situations, the final methods are notmarked as redundant even though they can't be extended by other classes/enums.
Nested enum
types are always static by default.
Final classes by definition cannot be extended so the final
modifier on the method of a final class is redundant.
Public modifier for constructors in non-public non-protected classesis always obsolete:
There is no violation in the following example,because removing public modifier from ProtectedInnerClassconstructor will make this code not compiling:
+
Checks for redundant modifiers.
Rationale: The Java Language Specification stronglydiscourages the usage of public
and abstract
for methoddeclarations in interface definitions as a matter of style.
The check validates:
public
or static
.enum
definitions that are declaredas static
.record
definitions that are declared as final
and nestedrecord
definitions that are declared as static
.interfaces by definition are abstract so the abstract
modifier isredundant on them.
Type declarations nested under interfaces by definition are public and static,so the public
and static
modifiers on nested typedeclarations are redundant. On the other hand, classes inside of interfaces canbe abstract or non abstract. So, abstract
modifier is allowed.
Fields in interfaces and annotations are automaticallypublic, static and final, so these modifiers are redundant aswell.
As annotations are a form of interface, their fields are alsoautomatically public, static and final just as theirannotation fields are automatically public and abstract.
A record class is implicitly final and cannot be abstract, these restrictions emphasizethat the API of a record class is defined solely by its state description, and cannot beenhanced later by another class. Nested records are implicitly static. This avoids animmediately enclosing instance which would silently add state to the record class.See JEP 395 for more info.
Enums by definition are static implicit subclasses of java.lang.Enum<E>.So, the static
modifier on the enums is redundant. In addition,if enum is inside of interface, public
modifier is also redundant.
Enums can also contain abstract methods and methods which can be overridden by thedeclared enumeration fields.See the following example:
Since these methods can be overridden in these situations, the final methods are notmarked as redundant even though they can't be extended by other classes/enums.
Nested enum
types are always static by default.
Final classes by definition cannot be extended so the final
modifier on the method of a final class is redundant.
Public modifier for constructors in non-public non-protected classesis always obsolete:
There is no violation in the following example,because removing public modifier from ProtectedInnerClassconstructor will make this code not compiling:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.modifier ".OverviewCheck": {} com.puppycrawl.tools.checkstyle.checks.naming.AbbreviationAsWordInNameCheck: Description: | -Validates abbreviations (consecutive capital letters) length in identifier name,it also allows to enforce camel case naming. Please read more atGoogle Style Guideto get to know how to avoid long abbreviations in names.
allowedAbbreviationLength
specifies how many consecutive capital letters areallowed in the identifier.A value of 3 indicates that up to 4 consecutive capital letters are allowed,one after the other, before a violation is printed. The identifier 'MyTEST' would beallowed, but 'MyTESTS' would not be.A value of 0 indicates that only 1 consecutive capital letter is allowed. Thisis what should be used to enforce strict camel casing. The identifier 'MyTest' wouldbe allowed, but 'MyTEst' would not be.
ignoreFinal
, ignoreStatic
, and ignoreStaticFinal
control whether variables with the respective modifiers are to be ignored.Note that a variable that is both static and final will always be considered underignoreStaticFinal
only, regardless of the values of ignoreFinal
and ignoreStatic
. So for example if ignoreStatic
is true butignoreStaticFinal
is false, then static final variables will not be ignored.
+
Validates abbreviations (consecutive capital letters) length in identifier name,it also allows to enforce camel case naming. Please read more atGoogle Style Guideto get to know how to avoid long abbreviations in names.
'_' is considered as word separator in identifier name.
allowedAbbreviationLength
specifies how many consecutive capital letters areallowed in the identifier.A value of 3 indicates that up to 4 consecutive capital letters are allowed,one after the other, before a violation is printed. The identifier 'MyTEST' would beallowed, but 'MyTESTS' would not be.A value of 0 indicates that only 1 consecutive capital letter is allowed. Thisis what should be used to enforce strict camel casing. The identifier 'MyTest' wouldbe allowed, but 'MyTEst' would not be.
ignoreFinal
, ignoreStatic
, and ignoreStaticFinal
control whether variables with the respective modifiers are to be ignored.Note that a variable that is both static and final will always be considered underignoreStaticFinal
only, regardless of the values of ignoreFinal
and ignoreStatic
. So for example if ignoreStatic
is true butignoreStaticFinal
is false, then static final variables will not be ignored.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.naming com.puppycrawl.tools.checkstyle.checks.naming.AbstractClassNameCheck: Description: | -Ensures that the names of abstract classes conforming to some regular expression andcheck that abstract
modifier exists.
Rationale: Abstract classes are convenience base class implementations ofinterfaces, not types as such. As such they should be named to indicate this.Also if names of classes starts with 'Abstract' it's very convenient thatthey will have abstract modifier.
+
Ensures that the names of abstract classes conforming to some pattern andcheck that abstract
modifier exists.
Rationale: Abstract classes are convenience base class implementations ofinterfaces, not types as such. As such they should be named to indicate this.Also, if names of classes starts with 'Abstract' it's very convenient thatthey will have abstract modifier.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.naming @@ -884,7 +890,7 @@ com.puppycrawl.tools.checkstyle.checks.naming.ConstantNameCheck: Package: com.puppycrawl.tools.checkstyle.checks.naming "com.puppycrawl.tools.checkstyle.checks.naming
.IllegalIdentifierNameCheck": Description: | -Checks identifiers with a regular expression for a set of illegal names, such as thosethat are restricted or contextual keywords. Examples include "yield", "record","_", and "var". Please read more atJava Language Specificationto get to know more about restricted keywords. Since this check uses aregular expression to specify valid identifiers, users can also prohibit the usageof certain symbols, such as "$", or any non-ascii character.
+
Checks identifiers with a pattern for a set of illegal names, such as thosethat are restricted or contextual keywords. Examples include "yield", "record","_", and "var". Please read more atJava Language Specificationto get to know more about restricted keywords. Since this check uses apattern to specify valid identifiers, users can also prohibit the usageof certain symbols, such as "$", or any non-ascii character.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: "com.puppycrawl.tools.checkstyle.checks.naming
" @@ -932,7 +938,7 @@ com.puppycrawl.tools.checkstyle.checks.naming.MethodTypeParameterNameCheck: Package: com.puppycrawl.tools.checkstyle.checks.naming com.puppycrawl.tools.checkstyle.checks.naming.PackageNameCheck: Description: | -Checks that package names conform to a specified pattern.
The default value of format
for module PackageName
has beenchosen to match the requirements in the JavaLanguage specification and the Sun coding conventions. Howeverboth underscores and uppercase letters are rather uncommon, so mostconfigurations should probably assign value ^[a-z]+(\.[a-z][a-z0-9]*)*$
toformat
for module PackageName
.
+
Checks that package names conform to a specified pattern.
The default value of format
for module PackageName
has beenchosen to match the requirements in the JavaLanguage specification and the Sun coding conventions. However,both underscores and uppercase letters are rather uncommon, so mostconfigurations should probably assign value ^[a-z]+(\.[a-z][a-z0-9]*)*$
toformat
for module PackageName
.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.naming @@ -948,6 +954,12 @@ com.puppycrawl.tools.checkstyle.checks.naming.PatternVariableNameCheck: This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project. Package: com.puppycrawl.tools.checkstyle.checks.naming +"com.puppycrawl.tools.checkstyle.checks.naming
.RecordComponentNameCheck": + Description: | +Checks that record component names conform to a specified pattern.
+ This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project. +
+ Package: "com.puppycrawl.tools.checkstyle.checks.naming
" "com.puppycrawl.tools.checkstyle.checks.naming
.RecordTypeParameterNameCheck": Description: |Checks that record type parameter names conform to a specified pattern.
@@ -968,7 +980,7 @@ com.puppycrawl.tools.checkstyle.checks.naming.TypeNameCheck: Package: com.puppycrawl.tools.checkstyle.checks.naming com.puppycrawl.tools.checkstyle.checks.regexp.RegexpCheck: Description: | -
Checks that a specified pattern exists, exists lessthan a set number of times, or does not exist in the file.
This check combines all the functionality provided byRegexpHeaderexcept supplying the regular expression from a file.
It differs from them in that it works in multiline mode.Its regular expression can span multiple lines and it checks thisagainst the whole file at once.The others work in singleline mode.Their single or multiple regular expressions can only span one line.They check each of these against each line in the file in turn.
Note: Because of the different mode of operation there may besome changes in the regular expressions used to achieve a particular end.
In multiline mode...
^
means the beginning of a line, as opposed to beginning of theinput.\A
.$
means the end of a line, as opposed to the end of the input.\Z
.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 <. The regularexpression should be entered on one line.
+
Checks that a specified pattern exists, exists lessthan a set number of times, or does not exist in the file.
This check combines all the functionality provided byRegexpHeaderexcept supplying the regular expression from a file.
It differs from them in that it works in multiline mode.Its regular expression can span multiple lines and it checks thisagainst the whole file at once.The others work in single-line mode.Their single or multiple regular expressions can only span one line.They check each of these against each line in the file in turn.
Note: Because of the different mode of operation there may besome changes in the regular expressions used to achieve a particular end.
In multiline mode...
^
means the beginning of a line, as opposed to beginning of theinput.\A
.$
means the end of a line, as opposed to the end of the input.\Z
.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 <. The regularexpression should be entered on one line.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.regexp @@ -980,25 +992,25 @@ com.puppycrawl.tools.checkstyle.checks.regexp.RegexpMultilineCheck: Package: com.puppycrawl.tools.checkstyle.checks.regexp com.puppycrawl.tools.checkstyle.checks.regexp.RegexpOnFilenameCheck: Description: | -Checks that a specified pattern matches based on file and/or folder path.It can also be used to verify files match specific namingpatterns not covered by other checks (Ex: properties, xml, etc.).
When customizing the check, the properties are applied in a specific order.The fileExtensions property first picks only files that match any of thespecific extensions supplied.Once files are matched against the fileExtensions, the match property is thenused in conjunction with the patterns to determine if the check is lookingfor a match or mis-match on those files. If the fileNamePattern issupplied, the matching is only applied to the fileNamePattern and not thefolderPattern. If no fileNamePattern is supplied, then matching is appliedto the folderPattern only and will result in all files in a folder to bereported on violations. If no folderPattern is supplied, then all foldersthat checkstyle finds are examined for violations.The ignoreFileNameExtensions property drops the file extension and appliesthe fileNamePattern only to the rest of file name. For example, if the file isnamed 'test.java' and this property is turned on, the pattern is only appliedto 'test'.
If this check is configured with no properties, then the default behaviorof this check is to report file names with spaces in them.When at least one pattern property is supplied, the entire check is underthe user's control to allow them to fully customize the behavior.
It is recommended that if you create your own pattern, to alsospecify a custom violation message. This allows the violation message printedto be clear what the violation is, especially if multiple RegexpOnFilenamechecks are used.Argument 0 for the message populates the check's folderPattern.Argument 1 for the message populates the check's fileNamePattern.The file name is not passed as an argument since it is part of CheckStyle'sdefault violation messages.
+
Checks that a specified pattern matches based on file and/or folder path.It can also be used to verify files match specific namingpatterns not covered by other checks (Ex: properties, xml, etc.).
When customizing the check, the properties are applied in a specific order.The fileExtensions property first picks only files that match any of thespecific extensions supplied.Once files are matched against the fileExtensions, the match property is thenused in conjunction with the patterns to determine if the check is lookingfor a match or mismatch on those files. If the fileNamePattern issupplied, the matching is only applied to the fileNamePattern and not thefolderPattern. If no fileNamePattern is supplied, then matching is appliedto the folderPattern only and will result in all files in a folder to bereported on violations. If no folderPattern is supplied, then all foldersthat checkstyle finds are examined for violations.The ignoreFileNameExtensions property drops the file extension and appliesthe fileNamePattern only to the rest of file name. For example, if the file isnamed 'test.java' and this property is turned on, the pattern is only appliedto 'test'.
If this check is configured with no properties, then the default behaviorof this check is to report file names with spaces in them.When at least one pattern property is supplied, the entire check is underthe user's control to allow them to fully customize the behavior.
It is recommended that if you create your own pattern, to alsospecify a custom violation message. This allows the violation message printedto be clear what the violation is, especially if multiple RegexpOnFilenamechecks are used.Argument 0 for the message populates the check's folderPattern.Argument 1 for the message populates the check's fileNamePattern.The file name is not passed as an argument since it is part of CheckStyle'sdefault violation messages.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.regexp com.puppycrawl.tools.checkstyle.checks.regexp.RegexpSinglelineCheck: Description: | -Checks that a specified pattern matches a single line in any file type.
Rationale: This check can be used to prototype checks and tofind common bad practice such as calling ex.printStacktrace()
, System.out.println()
, System.exit()
, etc.
+
Checks that a specified pattern matches a single-line in any file type.
Rationale: This check can be used to prototype checks and tofind common bad practice such as calling ex.printStacktrace()
, System.out.println()
, System.exit()
, etc.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.regexp com.puppycrawl.tools.checkstyle.checks.regexp.RegexpSinglelineJavaCheck: Description: | -Checks that a specified pattern matches a single line in Java files.
This class is variation onRegexpSingleline for detectingsingle lines that match a supplied regular expression in Java files. It supportssuppressing matches in Java comments.
+
Checks that a specified pattern matches a single-line in Java files.
This class is variation onRegexpSingleline for detectingsingle-lines that match a supplied regular expression in Java files. It supportssuppressing matches in Java comments.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.regexp com.puppycrawl.tools.checkstyle.checks.sizes.AnonInnerLengthCheck: Description: | -Checks for long anonymous inner classes.
Rationale: If an anonymous inner class becomes very long it is hardto understand and to see the flow of the method where the class isdefined. Therefore long anonymous inner classes should usually berefactored into a named inner class. See also Bloch, EffectiveJava, p. 93.
+
Checks for long anonymous inner classes.
Rationale: If an anonymous inner class becomes very long it is hardto understand and to see the flow of the method where the class isdefined. Therefore, long anonymous inner classes should usually berefactored into a named inner class. See also Bloch, EffectiveJava, p. 93.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.sizes @@ -1010,13 +1022,13 @@ com.puppycrawl.tools.checkstyle.checks.sizes.ExecutableStatementCountCheck: Package: com.puppycrawl.tools.checkstyle.checks.sizes com.puppycrawl.tools.checkstyle.checks.sizes.FileLengthCheck: Description: | -Checks for long source files.
Rationale: If a source file becomes very long it is hard tounderstand. Therefore long classes should usually be refactoredinto several individual classes that focus on a specific task.
+
Checks for long source files.
Rationale: If a source file becomes very long it is hard tounderstand. Therefore, long classes should usually be refactoredinto several individual classes that focus on a specific task.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.sizes com.puppycrawl.tools.checkstyle.checks.sizes.LambdaBodyLengthCheck: Description: | -Checks lambda body length.
Rationale: Similar to anonymous inner classes, if lambda body becomes very longit is hard to understand and to see the flow of the methodwhere the lambda is defined. Therefore long lambda bodyshould usually be extracted to method.
+
Checks lambda body length.
Rationale: Similar to anonymous inner classes, if lambda body becomes very longit is hard to understand and to see the flow of the methodwhere the lambda is defined. Therefore, long lambda bodyshould usually be extracted to method.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.sizes @@ -1034,7 +1046,7 @@ com.puppycrawl.tools.checkstyle.checks.sizes.MethodCountCheck: Package: com.puppycrawl.tools.checkstyle.checks.sizes com.puppycrawl.tools.checkstyle.checks.sizes.MethodLengthCheck: Description: | -Checks for long methods and constructors.
Rationale: If a method becomes very long it is hard tounderstand. Therefore long methods should usually be refactored intoseveral individual methods that focus on a specific task.
+
Checks for long methods and constructors.
Rationale: If a method becomes very long it is hard tounderstand. Therefore, long methods should usually be refactored intoseveral individual methods that focus on a specific task.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.sizes @@ -1056,10 +1068,9 @@ com.puppycrawl.tools.checkstyle.checks.sizes.RecordComponentNumberCheck: This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project. Package: com.puppycrawl.tools.checkstyle.checks.sizes -".Caching SupportCheck": {} -".Localisation SupportCheck": {} -".Base directory supportCheck": {} +".Localization SupportCheck": {} ".Enable External DTD loadCheck": {} +".Property chaining supportCheck": {} com.puppycrawl.tools.checkstyle.checks.whitespace.EmptyForInitializerPadCheck: Description: |Checks the padding of an empty for initializer; that is whethera white space is required at an empty for initializer, or such whitespace is forbidden. No check occurs if there is a line wrap at theinitializer, as in
@@ -1074,7 +1085,7 @@ com.puppycrawl.tools.checkstyle.checks.whitespace.EmptyForIteratorPadCheck: Package: com.puppycrawl.tools.checkstyle.checks.whitespace com.puppycrawl.tools.checkstyle.checks.whitespace.EmptyLineSeparatorCheck: Description: | -
Checks for empty line separators after header, package, all import declarations,fields, constructors, methods, nested classes,static initializers and instance initializers.
ATTENTION: empty line separator is required between token siblings,not after line where token is found.If token does not have same type sibling then empty lineis required at its end (for example for CLASS_DEF it is after '}').Also, trailing comments are skipped.
ATTENTION: violations from multiple empty lines cannot be suppressed via XPath:#8179.
+
Checks for empty line separators before package, all import declarations,fields, constructors, methods, nested classes,static initializers and instance initializers.
Checks for empty line separators before not only statements butimplementation and documentation comments and blocks as well.
ATTENTION: empty line separator is required between token siblings,not after line where token is found.If token does not have a sibling of the same type, then empty lineis required at its end (for example for CLASS_DEF it is after '}').Also, trailing comments are skipped.
ATTENTION: violations from multiple empty lines cannot be suppressed via XPath:#8179.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.whitespace @@ -1086,7 +1097,7 @@ com.puppycrawl.tools.checkstyle.checks.whitespace.FileTabCharacterCheck: Package: com.puppycrawl.tools.checkstyle.checks.whitespace com.puppycrawl.tools.checkstyle.checks.whitespace.GenericWhitespaceCheck: Description: | -Checks that the whitespace around the Generic tokens (angle brackets)"<" and ">" are correct to the typical convention.The convention is not configurable.
Left angle bracket ("<"):
Right angle bracket (">"):
+
Checks that the whitespace around the Generic tokens (angle brackets)"<" and ">" are correct to the typical convention.The convention is not configurable.
Left angle bracket ("<"):
Right angle bracket (">"):
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.whitespace @@ -1098,19 +1109,25 @@ com.puppycrawl.tools.checkstyle.checks.whitespace.MethodParamPadCheck: Package: com.puppycrawl.tools.checkstyle.checks.whitespace com.puppycrawl.tools.checkstyle.checks.whitespace.NoLineWrapCheck: Description: | -Checks that chosen statements are not line-wrapped. By default thisCheck restricts wrapping import and package statements, but it's possible to checkany statement.
+
Checks that chosen statements are not line-wrapped. By default, thisCheck restricts wrapping import and package statements, but it's possible to checkany statement.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.whitespace com.puppycrawl.tools.checkstyle.checks.whitespace.NoWhitespaceAfterCheck: Description: | -Checks that there is no whitespace after a token. More specifically,it checks that it is not followed by whitespace, or (if linebreaksare allowed) all characters on the line after are whitespace. Toforbid linebreaks after a token, set property allowLineBreaks
to false
.
The check processesARRAY_DECLARATORandINDEX_OPtokens specially from other tokens. Actually it is checked that there isno whitespace before this tokens, not after them.Space after theANNOTATIONS beforeARRAY_DECLARATORandINDEX_OPwill be ignored.
+
Checks that there is no whitespace after a token. More specifically,it checks that it is not followed by whitespace, or (if linebreaksare allowed) all characters on the line after are whitespace. Toforbid linebreaks after a token, set property allowLineBreaks
to false
.
The check processesARRAY_DECLARATORandINDEX_OPtokens specially from other tokens. Actually it is checked that there isno whitespace before these tokens, not after them.Space after theANNOTATIONS beforeARRAY_DECLARATORandINDEX_OPwill be ignored.
If the annotation is between the type and the array,like char @NotNull [] param
, the check will skipvalidation for spaces.
Note: This check processes theLITERAL_SYNCHRONIZED token only when it appears as a part of asynchronized statement, i.e. synchronized(this) {}
.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.whitespace com.puppycrawl.tools.checkstyle.checks.whitespace.NoWhitespaceBeforeCheck: Description: | -Checks that there is no whitespace before a token. Morespecifically, it checks that it is not preceded with whitespace, or(if linebreaks are allowed) all characters on the line before arewhitespace. To allow linebreaks before a token, set propertyallowLineBreaks
to true
. No check occursbefore semi-colons in empty for loop initializers or conditions.
+
Checks that there is no whitespace before a token. Morespecifically, it checks that it is not preceded with whitespace, or(if linebreaks are allowed) all characters on the line before arewhitespace. To allow linebreaks before a token, set propertyallowLineBreaks
to true
. No check occursbefore semicolons in empty for loop initializers or conditions.
+ This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project. +
+ Package: com.puppycrawl.tools.checkstyle.checks.whitespace +com.puppycrawl.tools.checkstyle.checks.whitespace.NoWhitespaceBeforeCaseDefaultColonCheck: + Description: | +Checks that there is no whitespace before the colon in a switch block.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.whitespace @@ -1122,7 +1139,7 @@ com.puppycrawl.tools.checkstyle.checks.whitespace.OperatorWrapCheck: Package: com.puppycrawl.tools.checkstyle.checks.whitespace com.puppycrawl.tools.checkstyle.checks.whitespace.ParenPadCheck: Description: | -Checks the policy on the padding of parentheses; that is whether aspace is required after a left parenthesis and before a rightparenthesis, or such spaces are forbidden. No check occurs atthe right parenthesis after an empty for iterator, at the leftparenthesis before an empty for initialization, or at the rightparenthesis of a try-with-resources resource specification wherethe last resource variable has a trailing semi-colon.Use Check EmptyForIteratorPad to validate empty for iterators andEmptyForInitializerPad to validate empty for initializers.Typecasts are also not checked, as there isTypecastParenPad to validate them.
+
Checks the policy on the padding of parentheses; that is whether aspace is required after a left parenthesis and before a rightparenthesis, or such spaces are forbidden. No check occurs atthe right parenthesis after an empty for iterator, at the leftparenthesis before an empty for initialization, or at the rightparenthesis of a try-with-resources resource specification wherethe last resource variable has a trailing semicolon.Use Check EmptyForIteratorPad to validate empty for iterators andEmptyForInitializerPad to validate empty for initializers.Typecasts are also not checked, as there isTypecastParenPad to validate them.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.whitespace @@ -1134,7 +1151,7 @@ com.puppycrawl.tools.checkstyle.checks.whitespace.SeparatorWrapCheck: Package: com.puppycrawl.tools.checkstyle.checks.whitespace com.puppycrawl.tools.checkstyle.checks.whitespace.SingleSpaceSeparatorCheck: Description: | -Checks that non-whitespace characters are separated by no more than onewhitespace. Separating characters by tabs or multiple spaces will bereported. Currently the check doesn't permit horizontal alignment. To inspectwhitespaces before and after comments, set the propertyvalidateComments
to true.
Setting validateComments
to false will ignore cases like:
Sometimes, users like to space similar items on different lines to the samecolumn position for easier reading. This feature isn't supported by thischeck, so both braces in the following case will be reported as violations.
+
Checks that non-whitespace characters are separated by no more than onewhitespace. Separating characters by tabs or multiple spaces will bereported. Currently, the check doesn't permit horizontal alignment. To inspectwhitespaces before and after comments, set the propertyvalidateComments
to true.
Setting validateComments
to false will ignore cases like:
Sometimes, users like to space similar items on different lines to the samecolumn position for easier reading. This feature isn't supported by thischeck, so both braces in the following case will be reported as violations.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.whitespace diff --git a/config/codeclimate_checkstyle.xml b/config/codeclimate_checkstyle.xml index 34bd873..17c7263 100644 --- a/config/codeclimate_checkstyle.xml +++ b/config/codeclimate_checkstyle.xml @@ -125,7 +125,6 @@