From 55d33b637d70d64011e79c23ec30a4e5a51305cb Mon Sep 17 00:00:00 2001
From: Abby Edwards Since Checkstyle 6.0 Check location of annotation on language elements.By default, Check enforce to locate annotations immediatelyafter documentation block and before target element, annotation should be located on separate line from target element. Attention: Annotations among modifiers are ignored (looks like false-negative)as there might be a problem with annotations for return types Example:
+ Check location of annotation on language elements.By default, Check enforce to locate annotations immediately after documentation blockand before target element, annotation should be located on separate line from targetelement. This check also verifies that the annotations are on the same indenting level asthe annotated element if they are not on the same line. Attention: Elements that cannot have JavaDoc comments like local variables are not in thescope of this check even though a token type like Attention: Annotations among modifiers are ignored (looks like false-negative)as there might be a problem with annotations for return types: Such annotations are better to keep close to type.Due to limitations, Checkstyle can not examine the target of an annotation. Example:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 8.2 The check does verifying that annotations are located on the same line with their targets.Verifying with this check is not good practice, but it is using by some style guides.
+ The check does verifying that annotations are located on the same line with their targets.Verifying with this check is not good practice, but it is using by some style guides.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 5.0 This check controls the style with the usage of annotations.
+ This check controls the style with the usage of annotations. Annotations have three element styles starting with the least verbose. To not enforce an element style a 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.
Since Checkstyle 5.0 Verifies that both the java.lang.Deprecated annotation ispresent and the @deprecated Javadoc tag is present wheneither is present.
+ Verifies that both the @Deprecated annotation is presentand the @deprecated javadoc tag are present when either one is present. Both ways of flagging deprecation serve their own purpose.The @Deprecated annotation is used for compilers and development tools.The @deprecated javadoc tag is used to document why something is deprecatedand what, if any, alternatives exist. In order to properly mark something as deprecated both forms ofdeprecation should be present. Package deprecation is a exception to the rule of always using thejavadoc tag and annotation to deprecate. It is not clear if thejavadoc tool will support it or not as newer versions keep flip floppingon if it is supported or will cause an error.See JDK-8160601.The deprecated javadoc tag is currently the only way to say why the packageis deprecated and what to use instead. Until this is resolved, if youdon't want to print violations on package-info, you can use afilter to ignore these files untilthe javadoc tool faithfully supports it. An example config usingSuppressionSingleFilter is:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 5.0 Verifies that the java.lang.Override annotation is presentwhen the {@inheritDoc} javadoc tag is present.
+ Verifies that the @Override annotation is presentwhen the @inheritDoc javadoc tag is present. Rationale: The @Override annotation helpscompiler tools ensure that an override is actually occurring. It isquite easy to accidentally overload a method or hide a static methodand using the @Override annotation points out these problems. This check will log a violation if using the @inheritDoc tag on a method thatis not valid (ex: private, or static method). There is a slight difference between the @Override annotation in Java 5 versusJava 6 and above. In Java 5, any method overridden from an interface cannotbe annotated with @Override. In Java 6 this behavior is allowed. As a result of the aforementioned difference between Java 5 and Java 6, aproperty called
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 5.0 This check makes sure that all package annotations are in thepackage-info.java file. According to the Java Language Specification. The JLS does not enforce the placement of package annotations.This placement may vary based on implementation. The JLSdoes highly recommend that all package annotations areplaced in the package-info.java file.See Java Language Specification, section 7.4.1.
+ This check makes sure that all package annotations are in thepackage-info.java file. According to the Java Language Specification. The JLS does not enforce the placement of package annotations.This placement may vary based on implementation. The JLSdoes highly recommend that all package annotations areplaced in the package-info.java file.See Java Language Specification, §7.4.1.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 5.0 This check allows you to specify what warnings thatSuppressWarnings is not allowed to suppress.You can also specify a list of TokenTypes thatthe configured warning(s) cannot be suppressed on. Limitations: This check does not consider conditionalsinside the SuppressWarnings annotation.
+ This check allows you to specify what warnings that@SuppressWarnings is not allowed to suppress.You can also specify a list of TokenTypes thatthe configured warning(s) cannot be suppressed on. Limitations: This check does not consider conditionalsinside the @SuppressWarnings annotation. For example: By default, any warning specified will be disallowed onall legal TokenTypes unless otherwise specified viathe tokens property. Also, by default warnings that are empty strings or allwhitespace (regex: ^$|^\s+$) are flagged. By specifying,the format property these defaults no longer apply. This check can be configured so that the "unchecked"and "unused" warnings cannot be suppressed onanything but variable and parameter declarations.See below of an example.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 5.7 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.
Since Checkstyle 3.1 Finds nested blocks, i.e. blocks that are used freely in the code. Rationale: Nested blocks are often leftovers from thedebugging process, they confuse the reader. For example this Check finds the obsolete braces in 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, i.e. blocks that are used freely in the code. Rationale: Nested blocks are often leftovers from thedebugging process, they confuse the reader. For example this Check finds the obsolete braces in 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.
Since Checkstyle 3.0 Checks for empty blocks. This check does not validate sequential blocks. Sequential blocks won't be checked. Also, no violations for fallthrough: This check processes LITERAL_CASE and LITERAL_DEFAULT separately.So, if tokens=LITERAL_DEFAULT, following code will not trigger any violation,as the empty block belongs to LITERAL_CASE: Configuration: Result:
+ Checks for empty blocks. This check does not validate sequential blocks. Sequential blocks won't be checked. Also, no violations for fallthrough: This check processes LITERAL_CASE and LITERAL_DEFAULT separately.So, if tokens=LITERAL_DEFAULT, following code will not trigger any violation,as the empty block belongs to LITERAL_CASE: Configuration: Result:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 6.4 Checks for empty catch blocks. There are two options to make validation more precise(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.
Since Checkstyle 3.0 Checks for the placement of left curly braces(
+ Checks for the placement of left curly braces(
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.0 Checks for braces around code blocks.
+ Checks for braces around code blocks.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.0 Checks the placement of right curly braces (
+ Checks the placement of right curly braces (
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.2 Checks that array initialization contains a trailing comma. The check demands a comma at the end if neither left nor right curly bracesare on the same line as the last element of the array. Rationale: Putting this comma in makes it easier to change the orderof the elements or add new elements on the end. Main benefit of a trailingcomma is that when you add new entry to an array, no surrounding lines are changed. If closing brace is on the same line as training comma, this benefit is gone(as the Check does not demand a certain location of curly braces the followingtwo cases will not produce a violation): If opening brace is on the same line as training comma there's also (more arguable) problem:
+ Checks that array initialization contains a trailing comma. The check demands a comma at the end if neither left nor right curly bracesare on the same line as the last element of the array. Rationale: Putting this comma in makes it easier to change the orderof the elements or add new elements on the end. Main benefit of a trailingcomma is that when you add new entry to an array, no surrounding lines are changed. If closing brace is on the same line as training comma, this benefit is gone(as the check does not demand a certain location of curly braces the followingtwo cases will not produce a violation): If opening brace is on the same line as training comma there's also (more arguable)problem:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.1 Detects inline conditionals. Here is one example of an inline conditional: Rationale: Some developers find inline conditionals hard to read, sotheir employer's coding standards forbid them.
+ Detects inline conditionals. Here is one example of an inline conditional: Rationale: Some developers find inline conditionals hard to read, sotheir employer's coding standards forbid them.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.2 Checks that classes which define a covariant Inspired by Finding Bugs is Easy, chapter '2.3.1 Bad Covariant Definition of Equals (Eq)': Java classes may override the Programmers sometimes mistakenly use the type of their class This covariant version of This kind of bug is not obvious because it looks correct, and in circumstances wherethe class is accessed through the references of the class type (rather than a supertype),it will work correctly. However, the first time it is used in a container,the behavior might be mysterious. For these reasons, this type of bug can eludetesting and code inspections.
+ Checks that classes which define a covariant Covariant Notice: the enums are also checked, eventhough they cannot override Inspired by Finding Bugs is Easy, chapter '2.3.1 Bad Covariant Definition of Equals (Eq)': Java classes may override the Programmers sometimes mistakenly use the type of their class This covariant version of This kind of bug is not obvious because it looks correct, and in circumstances wherethe class is accessed through the references of the class type (rather than a supertype),it will work correctly. However, the first time it is used in a container,the behavior might be mysterious. For these reasons, this type of bug can eludetesting and code inspections.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.2 According to Code Conventions for the Java Programming Language , the partsof a class or interface declaration should appear in the followingorder: Purpose of ignore* option is to ignore related violations, however it still impacts on other class members. ATTENTION: the check skips class fields which haveforward referencesfrom validation due to the fact that we have Checkstyle's limitations to clearlydetect user intention of fields location and grouping. For example,
+ Checks the order in which parts of the class or interface declaration are defined. According to Code Conventions for the Java Programming Language , the partsof a class or interface declaration should appear in the followingorder: Purpose of ignore* option is to ignore related violations,however it still impacts on other class members. ATTENTION: the check skips class fields which haveforward referencesfrom validation due to the fact that we have Checkstyle's limitations to clearlydetect user intention of fields location and grouping. For example:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.4 Check that the Rationale: Java allows
+ Check that the Rationale: Java allows
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.1 Detects empty statements (standalone ";" semicolon).
+ Detects empty statements (standalone {@code ";"} semicolon).Empty statements often introduce bugs that are hard to spot, such as in
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 5.0 Checks that any combination of String literalsis on the left side of an equals() comparison.Also checks for String literals assigned to some field(such as Rationale: Calling the For example, this code: should be refactored to:
+ Checks that any combination of String literalsis on the left side of an Rationale: Calling the For example, this code: should be refactored to:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.0 Checks that classes that either override Rationale: The contract of
+ Checks that classes that either override Rationale: The contract of
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.2 Checks if any class or object member is explicitly initialized todefault for its type value ( Rationale: Each instance variable gets initialized twice, to thesame value. Java initializes each instance variable to its defaultvalue (0 or null) before performing any initialization specified inthe code. So in this case, x gets initialized to 0 twice, and bargets initialized to null twice. So there is a minor inefficiency.This style of coding is a holdover from C/C++ style coding, and itshows that the developer isn't really confident that Javainitializes instance variables to default values.
+ Checks if any class or object member is explicitly initialized todefault for its type value ( Rationale: Each instance variable gets initialized twice, to thesame value. Java initializes each instance variable to its default value(
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.4 Checks for fall-through in The check honors special comments to suppress the warning. Bydefault the text "fallthru", "fall through", "fallthrough","falls through" and "fallsthrough" are recognized (casesensitive). The comment containing these words must be all on one line, and mustbe on the last non-empty line before 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. Bydefault the text "fallthru", "fall through", "fallthrough","falls through" and "fallsthrough" are recognized (casesensitive). The comment containing these words must be all on one line, and mustbe on the last non-empty line before the Note: The check assumes that there is no unreachablecode in the The following fragment of code will NOT trigger the check,because of the comment "fallthru" and absence of any Java codein case 5.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.2 Checks that local variables that never have their values changed aredeclared final. The check can be configured to also check thatunchanged parameters are declared final.
+ Checks that local variables that never have their values changed aredeclared final. The check can be configured to also check thatunchanged parameters are declared final.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.0 Checks that a local variable or a parameter does not shadow a fieldthat is defined in the same class.
+ Checks that a local variable or a parameter does not shadow a fieldthat is defined in the same class.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.2 Checks that certain exception types do not appear in a Rationale:Catching java.lang.Exception, java.lang.Error orjava.lang.RuntimeException is almost never acceptable.Novice developers often simply catch Exception in anattempt to handle multiple exception classes. This unfortunatelyleads to code that inadvertently catches NullPointerException, OutOfMemoryError, etc.
+ Checks that certain exception types do not appear in a Rationale:catching
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.0 Checks for illegal instantiations where a factory method ispreferred. Rationale: Depending on the project, for some classes it might bepreferable to create instances through factory methods rather thancalling the constructor. A simple example is the Some extremely performance sensitive projects may require the use offactory methods for other classes as well, to enforce the usage ofnumber caches or object pools.
+ Checks for illegal instantiations where a factory method ispreferred. Rationale: Depending on the project, for some classes it might bepreferable to create instances through factory methods rather thancalling the constructor. A simple example is the Some extremely performance sensitive projects may require the use offactory methods for other classes as well, to enforce the usage ofnumber caches or object pools.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 4.0 This check can be used to ensure that types are not declaredto be thrown. Declaring that a method throws java.lang.Error orjava.lang.RuntimeException is almost never acceptable.
+ This check can be used to ensure that types are not declaredto be thrown. Declaring that a method throws
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.2 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.
Since Checkstyle 3.2 Checks specified tokens text for matching an illegal pattern from
+ Checks specified tokens text for matching an illegal pattern from
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.2 Checks that particular classes are never used as types in variabledeclarations, return values or parameters. Rationale: Helps reduce coupling on concrete classes.
+ Checks that particular classes or interfaces are never used. Rationale: Helps reduce coupling on concrete classes. For additional restriction of type usage see also:IllegalInstantiation,IllegalImport
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.0 Checks for assignments in subexpressions, such as in Rationale: With the exception of Note: Check allows usage of the popular assignment in
+ Checks for assignments in subexpressions, such as in Rationale: With the exception of Note: Check allows usage of the popular assignment in 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.
Since Checkstyle 3.1 Checks that there are no "magic numbers" where a magicnumber is a numeric literal that is not defined as a constant.By default, -1, 0, 1, and 2 are not considered to be magic numbers. It is fine to have one constant defining multiple numeric literals within one expression:
+ Checks that there are no"magic numbers" where a magicnumber is a numeric literal that is not defined as a constant.By default, -1, 0, 1, and 2 are not considered to be magic numbers. Constant definition is any variable/field that has 'final' modifier.It is fine to have one constant defining multiple numeric literals within one expression:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.4 Checks that classes (except abstract ones) define a constructor and don'trely on the default one.
+ Checks that classes (except abstract ones) define a constructor and don'trely on the default one.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.1 Checks that switch statement has a "default" clause. Rationale: It's usually a good idea to introduce a default case inevery switch statement. Even if the developer is sure that allcurrently possible cases are covered, this should be expressed inthe default branch, e.g. by using an assertion. This way the code isprotected against later changes, e.g. introduction of new types in anenumeration type.
+ Checks that switch statement has a "default" clause. Rationale: It's usually a good idea to introduce a default case inevery switch statement. Even if the developer is sure that allcurrently possible cases are covered, this should be expressed inthe default branch, e.g. by using an assertion. This way the code isprotected against later changes, e.g. introduction of new types in anenumeration type.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.5 Check for ensuring that for loop control variables are not modified inside the for block. An example is: Rationale: If the control variable is modified inside the loopbody, the program flow becomes more difficult to follow. Such loop would be suppressed:
+ Check for ensuring 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:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.5 Checks for multiple occurrences of the same string literal within asingle file. Rationale: Code duplication makes maintenance more difficult, so itcan be better to replace the multiple occurrences with a constant.
+ Checks for multiple occurrences of the same string literal within asingle file. Rationale: Code duplication makes maintenance more difficult, so itcan be better to replace the multiple occurrences with a constant.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.4 Checks that each variable declaration is in its own statement and onits own line. Rationale: the Java code conventions chapter 6.1 recommends thatdeclarations should be one per line/statement.
+ Checks that each variable declaration is in its own statement and onits own line. Rationale: the Java code conventions chapter 6.1 recommends thatdeclarations should be one per line/statement.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 5.3 Restricts nested
+ Restricts nested
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.2 Restricts nested if-else blocks to a specified depth (default = 1).
+ Restricts nested if-else blocks to a specified depth (default = 1).
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.2 Restricts nested try blocks to a specified depth (default = 1).
+ Restricts nested try blocks to a specified depth (default = 1).
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 5.0 Checks that the clone method is not overridden from theObject class. 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. This check is almost exactly the same as the {@link NoFinalizerCheck}
+ 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.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 5.0 Verifies there are no
+ Verifies there are no Rationale: Finalizers are unpredictable, often dangerous, and generally unnecessary.Their use can cause erratic behavior, poor performance, and portability problems.For more information for the finalize method and its issues, see Effective Java:Programming Language Guide Third Edition by Joshua Bloch, §8.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 5.3 Checks that there is only one statement per line. Rationale: It's very difficult to read multiple statements on one line. In the Java programming language, statements are the fundamental unit ofexecution. All statements except blocks are terminated by a semicolon.Blocks are denoted by open and close curly braces. OneStatementPerLineCheck checks the following types of statements:variable declaration statements, empty statements, import statements,assignment statements, expression statements, increment statements,object creation statements, 'for loop' statements, 'break' statements,'continue' statements, 'return' statements.
+ Checks that there is only one statement per line. Rationale: It's very difficult to read multiple statements on one line. In the Java programming language, statements are the fundamental unit ofexecution. All statements except blocks are terminated by a semicolon.Blocks are denoted by open and close curly braces. OneStatementPerLineCheck checks the following types of statements:variable declaration statements, empty statements, import statements,assignment statements, expression statements, increment statements,object creation statements, 'for loop' statements, 'break' statements,'continue' statements, 'return' statements, resources statements (optional).
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 5.8 Checks that overload methods are grouped together.
+ Checks that overload methods are grouped together.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.2 Ensures that a class has a package declaration, and (optionally) whetherthe package name matches the directory name for the source file. Rationale: Classes that live in the null package cannot beimported. Many novice developers are not aware of this. Packages provide logical namespace to classes and should be stored inthe form of directory levels to provide physical grouping to your classes.These directories are added to the classpath so that your classesare visible to JVM when it runs the code.
+ Ensures that a class has a package declaration, and (optionally) whetherthe package name matches the directory name for the source file. Rationale: Classes that live in the null package cannot beimported. Many novice developers are not aware of this. Packages provide logical namespace to classes and should be stored inthe form of directory levels to provide physical grouping to your classes.These directories are added to the classpath so that your classesare visible to JVM when it runs the code.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.2 Disallows assignment of parameters. Rationale: Parameter assignment is often considered poor programmingpractice. Forcing developers to declare parameters as final is oftenonerous. Having a check ensure that parameters are never assignedwould give the best of both worlds.
+ Disallows assignment of parameters. Rationale: Parameter assignment is often considered poor programmingpractice. Forcing developers to declare parameters as final is oftenonerous. Having a check ensure that parameters are never assignedwould give the best of both worlds.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.4 Checks that references to instance variables and methods of the presentobject are explicitly of the form "this.varName" or"this.methodName(args)" and that those references don'trely on the default behavior when "this." is absent. Warning: the Check is very controversial if 'validateOnlyOverlapping' option is set to'false' and not that actual nowadays. Rationale:
+ Checks that references to instance variables and methods of the presentobject are explicitly of the form "this.varName" or"this.methodName(args)" and that those references don'trely on the default behavior when "this." is absent. Warning: the Check is very controversial if 'validateOnlyOverlapping' option is set to'false' and not that actual nowadays. Rationale:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.2 Restricts the number of return statements in methods, constructors and lambda expressions(2 by default). Ignores specified methods ( max property will only check returns in methods and lambdas that return a specific value (Ex: 'return 1;'). maxForVoid property will only check returns in methods, constructors, and lambdas that have no return type (IE'return;').It will only count visible return statements. Return statements not normally written, but implied, atthe end of the method/constructor definition will not be taken into account.To disallow "return;" in void return type methods, use a value of 0. Rationale: Too many return points can mean that code isattempting to do too much or may be difficult to understand.
+ Restricts the number of return statements in methods, constructors and lambda expressions(2 by default). Ignores specified methods ( max property will only check returns in methods and lambdas that return a specificvalue (Ex: 'return 1;'). maxForVoid property will only check returns in methods, constructors, and lambdasthat have no return type (IE 'return;').It will only count visible return statements. Return statements not normally written, butimplied, at the end of the method/constructor definition will not be taken into account.To disallow "return;" in void return type methods, use a value of 0. Rationale: Too many return points can mean that code isattempting to do too much or may be difficult to understand.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.0 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 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.
Since Checkstyle 3.0 Checks for over-complicated boolean return statements. For examplethe following code could be written as The idea for this Check has been shamelessly stolen from theequivalent PMD rule.
+ Checks for over-complicated boolean return statements. For examplethe following code could be written as The idea for this Check has been shamelessly stolen from theequivalent PMD rule.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.2 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.
Since Checkstyle 3.2 Checks that an overriding Reference: Object.clone().
+ Checks that an overriding Reference: Object.clone().
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.2 Checks that an overriding Reference: Use Finalization Only When You Must.
+ Checks that an overriding References:How to Handle Java Finalization's Memory-Retention Issues;10 points on finalize method in Java.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.4 Checks for the use of unnecessary parentheses.
+ 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.
+ Checks if unnecessary semicolon is used after type member declaration.
+ This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
+ Checks if unnecessary semicolon is in enum definitions.Semicolon is not needed if enum body contains only enum constants.
+ This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
+ Checks if unnecessary semicolon is used in last resource declaration.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 5.8 Checks the distance between declaration of variable and its first usage.
+ Checks the distance between declaration of variable and its first usage.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.1 The check finds classes that are designed for extension (subclass creation). Nothing wrong could be with founded classes.This check makes sense only for library project (not an application projects)which care of ideal OOP-design to make sure that class works in all cases even misusage.Even in library projects this check most likely will find classes that are designedfor extension by somebody. User needs to use suppressions extensively to got a benefit fromthis check, and keep in suppressions all confirmed/known classes that are deigned forinheritance intentionally to let the check catch only new classes, and bring this toteam/user attention. ATTENTION: Only user can decide whether a class is designed for extension or not.The check just shows all classes which are possibly designed for extension.If smth inappropriate is found please use suppression. ATTENTION: If the method which can be overridden in a subclass has a javadoc comment(a good practice is to explain its self-use of overridable methods) the check will notrise a violation. The violation can also be skipped if the method which can be overriddenin a subclass has one or more annotations that are specified in ignoredAnnotationsoption. Note, that by default @Override annotation is not included in theignoredAnnotations set as in a subclass the method which has the annotation can also beoverridden in its subclass. Problem is described at "Effective Java, 2nd Edition by Josh Bloch" book, chapter "Item 17: Design and document for inheritance or else prohibit it". Some quotes from book: The check finds classes that have overridable methods (public or protected methodsthat are non-static, not-final, non-abstract) and have non-empty implementation. Rationale: This library design style protects superclasses againstbeing broken by subclasses. The downside is that subclasses arelimited in their flexibility, in particular they cannot preventexecution of code in the superclass, but that also means thatsubclasses cannot corrupt the state of the superclass by forgettingto call the superclass's method. More specifically,it enforces a programming style where superclasses provide empty"hooks" that can be implemented by subclasses. Example of code that cause violation as it is designed for extension: Example of code without violation:
+ The check finds classes that are designed for extension (subclass creation). Nothing wrong could be with founded classes.This check makes sense only for library projects (not application projects)which care of ideal OOP-design to make sure that class works in all cases even misusage.Even in library projects this check most likely will find classes that are designedfor extension by somebody. User needs to use suppressions extensively to got a benefitfrom this check, and keep in suppressions all confirmed/known classes that are deignedfor inheritance intentionally to let the check catch only new classes, and bring this toteam/user attention. ATTENTION: Only user can decide whether a class is designed for extension or not.The check just shows all classes which are possibly designed for extension.If smth inappropriate is found please use suppression. ATTENTION: If the method which can be overridden in a subclass has a javadoc comment(a good practice is to explain its self-use of overridable methods) the check will notrise a violation. The violation can also be skipped if the method which can be overriddenin a subclass has one or more annotations that are specified in ignoredAnnotationsoption. Note, that by default @Override annotation is not included in theignoredAnnotations set as in a subclass the method which has the annotation can also beoverridden in its subclass. Problem is described at "Effective Java, 2nd Edition by Joshua Bloch" book, chapter"Item 17: Design and document for inheritance or else prohibit it". Some quotes from book: The check finds classes that have overridable methods (public or protected methodsthat are non-static, not-final, non-abstract) and have non-empty implementation. Rationale: This library design style protects superclasses againstbeing broken by subclasses. The downside is that subclasses arelimited in their flexibility, in particular they cannot preventexecution of code in the superclass, but that also means thatsubclasses cannot corrupt the state of the superclass by forgettingto call the superclass's method. More specifically,it enforces a programming style where superclasses provide empty"hooks" that can be implemented by subclasses. Example of code that cause violation as it is designed for extension: Example of code without violation:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.1 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
+ 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
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.1 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. 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:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 5.2 Check nested (inner) classes/interfaces are declared at thebottom of the class after all method and field declarations.
+ Check nested (inner) classes/interfaces are declared at thebottom of the class after all method and field declarations.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.1 Implements Joshua Bloch, Effective Java, Item 17 - Use Interfaces only todefine types. According to Bloch, an interface should describe a type.It is therefore inappropriate to define an interface that does notcontain any methods but only constants. The Standard class javax.swing.SwingConstantsis an example of a class that would be flagged by this check. The check can be configured to also disallow marker interfaces like
+ Implements Joshua Bloch, Effective Java, Item 17 - Use Interfaces only todefine types. According to Bloch, an interface should describe a type.It is therefore inappropriate to define an interface that does notcontain any methods but only constants. The Standard interface javax.swing.SwingConstantsis an example of an interface that would be flagged by this check. The check can be configured to also disallow marker interfaces like
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.2 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 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 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 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.
Since Checkstyle 5.8 Checks that each top-level class, interface orenum 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, enum or interface,top-level type is the first type in file.
+ Checks that each top-level class, interface orenum 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, enum or interface,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.
Since Checkstyle 3.2 Restricts throws statements to a specified count (4 by default).Methods with "Override" or "java.lang.Override" annotation are skippedfrom validation as current class cannot change signature of these methods. Rationale: Exceptions form part of a method's interface. Declaring amethod to throw too many differently rooted exceptions makesexception handling onerous and leads to poor programming practicessuch as writing code like ignorePrivateMethods - allows to skip private methods as they donot cause problems for other classes.
+ Restricts throws statements to a specified count (4 by default).Methods with "Override" or "java.lang.Override" annotation are skippedfrom validation as current class cannot change signature of these methods. Rationale: Exceptions form part of a method's interface. Declaring amethod to throw too many differently rooted exceptions makesexception handling onerous and leads to poor programming practicessuch as writing code like ignorePrivateMethods - allows to skip private methods as they donot cause problems for other classes.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.0 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 Public members are not flagged if the name matches the publicmember regular expression (contains Note thatCheckstyle 2 used to include 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.Default value is false allowPublicImmutableFields - which allows immutable fields to be declared aspublic if defined in final class. Default value is false Field is known to be immutable if:- It's declared as final- Has either a primitive type or instance of class user defined to be immutable(such as String, ImmutableCollection from Guava and etc) Classes known to be immutable are listed in immutableClassCanonicalNames by theircanonical names. Rationale: Forcing all fields of class to have private modified by default is goodin 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 Public members are not flagged if the name matches the publicmember regular expression (contains Note thatCheckstyle 2 used to include 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. Rationale: Forcing all fields of class to have private modifier by default is goodin 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.
Since Checkstyle 7.2 File filter 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 an 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 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 an 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.
Since Checkstyle 3.2 Filter
+ Filter
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.5 Filter 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 morethan one suppression comment each on separate line.
+ Filter 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 morethan one suppression comment each on separate line. Attention: This filter may only be specified within the TreeWalker module(
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.2 Filter
+ Filter
+ This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
+ Filter Rationale: To allow users use suppressions configured in the same config withother modules. SuppressionFilter and SuppressionXpathFilter are require separatefile. Advice: If checkstyle configuration is used for several projects, single suppressionson common files/folders is better to put in checkstyle configuration as common rule.All suppression that are for specific file names is better to keep in project specificconfig file. Attention: This filter only supports single suppression, and will needmultiple instances if users wants to suppress multiple violations.
+ This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
+ Filter Currently, filter supports the followingchecks: Note, that support for other Checks will be available after resolvingissue 4830. Currently, filter supports the followingxpath axes: You can use the command line helper tool to generate xpathsuppressions based on your configuration file and input files.Seeherefor more details.
+ This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
+ Filter Rationale: To allow users use suppressions configured in the same config withother modules. SuppressionFilter and SuppressionXpathFilter are require separatefile. Advice: If checkstyle configuration is used for several projects, single suppressionson common files/folders is better to put in checkstyle configuration as common rule.All suppression that are for specific file names is better to keep in project specificconfig file. Attention: This filter only supports single suppression, and will needmultiple instances if users wants to suppress multiple violations.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 5.7 Filter Rationale: Same as for 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 include
+ Filter Rationale: Same as for 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 include
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 5.0 Filter Rationale: Same as
+ Filter Rationale: Same as Attention: This filter may only be specified within the TreeWalker module(
+ This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
+ Filter 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.
Since Checkstyle 6.9 Checks that a source file begins with a specified header. Property Property Since the year information will change over time, you can tellCheckstyle to ignore line 4 by setting property
+ Since Checkstyle 6.9 Checks that a source file begins with a specified header. Property Property Since the year information will change over time, you can tellCheckstyle to ignore line 4 by setting property
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 5.8 Checks that the groups of import declarations appear in the order specifiedby the user. If there is an import but its group is not specified in theconfiguration such an import should be placed at the end of the import list. Examples section contains examples thatwork with default formatter configurations of Eclipse, IntelliJ IDEA and NetBeans
+ Checks that the groups of import declarations appear in the order specifiedby the user. If there is an import but its group is not specified in theconfiguration such an import should be placed at the end of the import list.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 3.0 Checks for imports from a set of illegal packages. By default, thecheck rejects all
+ Since Checkstyle 3.0 Checks for imports from a set of illegal packages. By default, thecheck rejects all
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Since Checkstyle 4.0 Controls what can be imported in each package. Useful forensuring that application layering rules are not violated,especially on large projects. Short description of the behaviour:
@Override
@Nullable
public String getNameIfPresent() { ... }
VARIABLE_DEF
would matchthem.
@Override
@Nullable
public String getNameIfPresent() { ... }
ElementStyle.COMPACT_NO_ARRAY
ElementStyle.COMPACT
ElementStyle.EXPANDED
ElementStyle.IGNORE
type is provided.The desired style can be set through the elementStyle
property.ElementStyle.EXPANDED
style is more verbose.The expanded version is sometimes referred to as "named parameters" in other languages.ElementStyle.COMPACT
style is less verbose.This style can only be used when there is an element called 'value' which is eitherthe sole element or all other elements have default values.ElementStyle.COMPACT_NO_ARRAY
style is less verbose.It is similar to the ElementStyle.COMPACT
style but single value arraysare flagged.With annotations a single value array does not need to be placed in an array initializer.ClosingParens.ALWAYS
type.To never have ending parenthesis use the ClosingParens.NEVER
type.To not enforce a closing parenthesis preference a ClosingParens.IGNORE
type is provided. Set this through the closingParens
property.TrailingArrayComma.ALWAYS
type.To never have a trailing comma use the TrailingArrayComma.NEVER
type.To not enforce a trailing array comma preference a TrailingArrayComma.IGNORE
type is provided.Set this through the trailingArrayComma
property.ElementStyle
is set to COMPACT_NO_ARRAY
,the TrailingArrayComma
is set to NEVER
,and the ClosingParens
is set to NEVER
.
<!-- 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>
javaFiveCompatibility
is available. Thisproperty will only check classes, interfaces, etc. that do not contain theextends or implements keyword or are not anonymous classes. This means itonly checks methods overridden from java.lang.Object
.Java 5 Compatibility mode severely limits this check. It is recommended toonly use it on Java 5 source.
For example: @SuppressWarnings((false) ? (true) ? "unchecked" : "foo" : "unused")According to the above example, the "unused" warning is being suppressednot the "unchecked" or "foo" warnings. All of these warnings will beconsidered and matched against regardless of what the conditionalevaluates to.
The check also does not support code like @SuppressWarnings("un" + "used")
,@SuppressWarnings((String) "unused")
or@SuppressWarnings({('u' + (char)'n') + (""+("used" + (String)"")),})
.@SuppressWarnings((false) ? (true) ? "unchecked" : "foo" : "unused")
.According to the above example, the "unused" warning is being suppressednot the "unchecked" or "foo" warnings. All of these warnings will beconsidered and matched against regardless of what the conditionalevaluates to.The check also does not support code like @SuppressWarnings("un" + "used")
,@SuppressWarnings((String) "unused")
or@SuppressWarnings({('u' + (char)'n') + (""+("used" + (String)"")),})
.@SuppressWarnings
annotations. It allows toprevent Checkstyle from reporting errors 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. You can also definealiases for check names that need to be suppressed.
public void guessTheOutput()
{
int whichIsWhich = 0;
{
int 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 1:
// OK if allowInSwitchCase is true
{
System.out.println("Hello");
x = 2;
break;
}
}
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;
}
}
switch (a) {
case 1: // no violation
case 2: // no violation
case 3: someMethod(); { } // no violation
default: break;
}
<module name="EmptyBlock">
<property name="tokens" value="LITERAL_DEFAULT"/>
</module>
switch (a) {
default: // no violation for "default:" as empty block belong to "case 1:"
case 1: { }
}
switch (a) {
case 1: // no violation
case 2: // no violation
case 3: someMethod(); { } // no violation
default: break;
}
<module name="EmptyBlock">
<property name="tokens" value="LITERAL_DEFAULT"/>
</module>
switch (a) {
default: // no violation for "default:" as empty block belong to "case 1:"
case 1: { }
}
'{'
) for code blocks. The policy to verify isspecified using the property option
.'{'
) for code blocks.'}'
)for if-else, try-catch-finally blocks, while-loops, for-loops,method definitions, class definitions, constructor definitions,instance and static initialization blocks.The policy to verify is specified using the property option
.'}'
)for if-else, try-catch-finally blocks, while-loops, for-loops,method definitions, class definitions, constructor definitions,instance and static initialization blocks.For right curly brace of expression blocks please follow issue#5945.
int[] a = new int[]
{
1,
2,
3,
};
return new int[] { 0 };
return new int[] { 0
};
return new int[] {
0 };
{
100000000000000000000,
200000000000000000000, // OK
}
{
100000000000000000000,
200000000000000000000,
300000000000000000000, // Just this line added, no other changes
}
{100000000000000000000,
200000000000000000000,} // Trailing comma not needed, line needs to be modified anyway
{100000000000000000000,
200000000000000000000, // Modified line
300000000000000000000,} // Added line
{100000000000000000000, // Line cannot be just duplicated to slightly modify entry
}
{100000000000000000000,
100000000000000000001, // More work needed to duplicate
}
int[] a = new int[]
{
1,
2,
3,
};
return new int[] { 0 };
return new int[] { 0
};
return new int[] {
0 };
{
100000000000000000000,
200000000000000000000, // OK
}
{
100000000000000000000,
200000000000000000000,
300000000000000000000, // Just this line added, no other changes
}
{100000000000000000000,
200000000000000000000,} // Trailing comma not needed, line needs to be modified anyway
{100000000000000000000,
200000000000000000000, // Modified line
300000000000000000000,} // Added line
{100000000000000000000, // Line cannot be just duplicated to slightly modify entry
}
{100000000000000000000,
100000000000000000001, // More work needed to duplicate
}
String a = getParameter("a");
String b = (a==null || a.length<1) ? null : a.substring(1);
String a = getParameter("a");
String b = (a==null || a.length()<1) ? null : a.substring(1);
equals()
methodalso override method equals(Object)
.
Covariant equals()
- method that is similar to equals(Object)
,but with a covariant parameter type (any subtype of Object).
Notice: the enums are also checked, eventhough they cannot override equals(Object)
. The reason isto point out that implementing equals()
in enums is considered anawful practice: it may cause having two different enum values that are equal usingcovariant enum method, and not equal when compared normally.equals(Object)
method to definea predicate for object equality. This method is used by many of the Java runtimelibrary classes; for example, to implement generic containers.Foo
as the type of the parameter to equals()
:
public boolean equals(Foo obj) {...}
equals()
does not override the version in theObject
class, and it may lead to unexpected behavior at runtime,especially if the class is used with one of the standard collection classeswhich expect that the standard equals(Object)
method is overridden.equals()
methodalso override method equals(Object)
.equals()
- method that is similar to equals(Object)
,but with a covariant parameter type (any subtype of Object).equals(Object)
. The reason isto point out that implementing equals()
in enums is considered anawful practice: it may cause having two different enum values that are equal usingcovariant enum method, and not equal when compared normally.equals(Object)
method to definea predicate for object equality. This method is used by many of the Java runtimelibrary classes; for example, to implement generic containers.Foo
as the type of the parameter to equals()
:
public boolean equals(Foo obj) {...}
equals()
does not override the version in theObject
class, and it may lead to unexpected behavior at runtime,especially if the class is used with one of the standard collection classeswhich expect that the standard equals(Object)
method is overridden.
public class A {
private double x = 1.0;
private double y = 2.0;
public double slope = x / y; // will be skipped from validation due to forward reference
}
default
is after all thecase
s in a switch
statement.default
anywherewithin the switch
statement. But it ismore readable if it comes after the last case
.default
is after all thecases in a switch
statement.default
anywherewithin the switch
statement. But it ismore readable if it comes after the last case
.
if (someCondition);
doConditionalStuff();
doUnconditionalStuff();
someString.equals(anotherString = "text")
).equals()
method on String literals will avoid a potentialNullPointerException. Also, it is pretty common to see nullchecks right before equals comparisons, which is not necessaryin the example below.
String nullString = null;
nullString.equals("My_Sweet_String");
String nullString = null;
"My_Sweet_String".equals(nullString);
equals()
comparison.Also checks for String literals assigned to some field(such as someString.equals(anotherString = "text")
).equals()
method on String literals will avoid a potentialNullPointerException
. Also, it is pretty common to see nullchecks right before equals comparisons, which is not necessaryin the example below.
String nullString = null;
nullString.equals("My_Sweet_String");
String nullString = null;
"My_Sweet_String".equals(nullString);
equals()
or hashCode()
also overrides the other.This checks only verifies that the method declarations matchObject.equals(Object)}
and Object.hashCode()
exactly to beconsidered an override. This check does not verify invalid method names, parametersother than Object
, or anything else.equals()
andhashCode()
requires that equal objectshave the same hashCode. Therefore, whenever you override equals()
you must override hashCode()
to ensure that your class can be used inhash-based collections.equals()
or hashCode()
also overrides the other.This check only verifies that the method declarations matchObject.equals(Object)
and Object.hashCode()
exactly to beconsidered an override. This check does not verify invalid method names, parametersother than Object
, or anything else.equals()
andhashCode()
requires that equal objectshave the same hashCode. Therefore, whenever you overrideequals()
you must override hashCode()
to ensure that your class can be used in hash-based collections.null
forobject references, zero for numeric types and char
and false
forboolean
.null
forobject references, zero for numeric types and char
and false
forboolean
.0
or null
) before performing any initialization specified inthe code. So there is a minor inefficiency.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).
switch (i){
case 0:
i++; // fall through
case 1:
i++;
// falls through
case 2:
case 3:
case 4: {
i++;
}
// fallthrough
case 5:
i++;
/* fallthru */case 6:
i++
break;
}
case
.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).
switch (i) {
case 0:
i++; // fall through
case 1:
i++;
// falls through
case 2:
case 3:
case 4: {
i++;
}
// fallthrough
case 5:
i++;
/* fallthru */case 6:
i++
break;
}
case
.
case 3:
x = 2;
// fallthru
case 4:
case 5:
case 6:
break;
catch
statement.catch
statement.java.lang.Exception
, java.lang.Error
orjava.lang.RuntimeException
is almost never acceptable.Novice developers often simply catch Exception in anattempt to handle multiple exception classes. This unfortunatelyleads to code that inadvertently catches NullPointerException
,OutOfMemoryError
, etc.java.lang.Boolean
class. For performance reasons, it is preferable touse the predefined constants TRUE
andFALSE
. Constructor invocations should bereplaced by calls to Boolean.valueOf()
.java.lang.Boolean
class. For performance reasons, it is preferable touse the predefined constants TRUE
andFALSE
. Constructor invocations should bereplaced by calls to Boolean.valueOf()
.java.lang.Error
orjava.lang.RuntimeException
is almost never acceptable.format
property. By default no tokens are specified.format
property. By default no tokens are specified.String s = Integer.toString(i = 2);
.for
iterators and assignment inwhile
idiom, 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.while
idiom:!= null
and there is nochance that intention was to write line == reader.readLine()
.String s = Integer.toString(i = 2);
.for
iterators and assignment inwhile
idiom, 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.while
idiom:
String line;
while ((line = bufferedReader.readLine()) != null) {
// process the line
}
!= null
and there is nochance that intention was to write line == reader.readLine()
.
static final int SECONDS_PER_DAY = 24 * 60 * 60;
static final double SPECIAL_RATIO = 4.0 / 3.0;
static final double SPECIAL_SUM = 1 + Math.E;
static final double SPECIAL_DIFFERENCE = 4 - Math.PI;
static final Border STANDARD_BORDER = BorderFactory.createEmptyBorder(3, 3, 3, 3);
static final Integer ANSWER_TO_THE_ULTIMATE_QUESTION_OF_LIFE = new Integer(42);
for (int i = 0; i < 1; i++) {
i++; //violation
}
See FOR statement specification for more details.
for (int i = 0; i < 10;) {
i++;
}
for (int i = 0; i < 1; i++) {
i++; //violation
}
for (int i = 0; i < 10;) {
i++;
}
for
blocks to a specified depth(default = 1).for
blocks to a specified depth(default = 1).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
finalize()
methodsdefined in a class.finalize()
methodsdefined in a class.equals()
by default).equals()
by default). if (b == true)
, b || true
, !false
,etc. if (b == true)
, b || true
, !false
,etc.
if (valid())
return false;
else
return true;
return !valid();
if (valid())
return false;
else
return true;
return !valid();
==
or!=
.
if (x == "something")
if ("something".equals(x))
==
or!=
.
if (x == "something")
if ("something".equals(x))
clone()
method invokessuper.clone()
. Does not check native methods, asthey have no possible java defined implementation.clone()
method invokessuper.clone()
. Does not check native methods, asthey have no possible java defined implementation.finalize()
method invokessuper.finalize()
. Does not check native methods, asthey have no possible java defined implementation.finalize()
method invokessuper.finalize()
. Does not check native methods, asthey have no possible java defined implementation.
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
The class must document its self-use of overridable methods.By convention, a method that invokes overridable methods contains a descriptionof these invocations at the end of its documentation comment. The descriptionbegins with the phrase “This implementation.”
The best solution to this problem is to prohibit subclassing in classes thatare not designed and documented to be safely subclassed.
If a concrete class does not implement a standard interface, then you mayinconvenience some programmers by prohibiting inheritance. If you feel that youmust allow inheritance from such a class, one reasonable approach is to ensurethat the class never invokes any of its overridable methods and to document thisfact. In other words, eliminate the class’s self-use of overridable methods entirely.In doing so, you’ll create a class that is reasonably safe to subclass. Overriding amethod will never affect the behavior of any other method.
public abstract class Plant {
private String roots;
private String trunk;
protected void validate() {
if (roots == null) throw new IllegalArgumentException("No roots!");
if (trunk == null) throw new IllegalArgumentException("No trunk!");
}
public abstract void grow();
}
public class Tree extends Plant {
private List leaves;
@Overrides
protected void validate() {
super.validate();
if (leaves == null) throw new IllegalArgumentException("No leaves!");
}
public void grow() {
validate();
}
}
public abstract class Plant {
private String roots;
private String trunk;
private void validate() {
if (roots == null) throw new IllegalArgumentException("No roots!");
if (trunk == null) throw new IllegalArgumentException("No trunk!");
validateEx();
}
protected void validateEx() { }
public abstract void grow();
}
The class must document its self-use of overridable methods.By convention, a method that invokes overridable methods contains a descriptionof these invocations at the end of its documentation comment. The descriptionbegins with the phrase “This implementation.”
The best solution to this problem is to prohibit subclassing in classes thatare not designed and documented to be safely subclassed.
If a concrete class does not implement a standard interface, then you mayinconvenience some programmers by prohibiting inheritance. If you feel that youmust allow inheritance from such a class, one reasonable approach is to ensurethat the class never invokes any of its overridable methods and to document thisfact. In other words, eliminate the class’s self-use of overridable methods entirely.In doing so, you’ll create a class that is reasonably safe to subclass. Overriding amethod will never affect the behavior of any other method.
public abstract class Plant {
private String roots;
private String trunk;
protected void validate() {
if (roots == null) throw new IllegalArgumentException("No roots!");
if (trunk == null) throw new IllegalArgumentException("No trunk!");
}
public abstract void grow();
}
public class Tree extends Plant {
private List leaves;
@Overrides
protected void validate() {
super.validate();
if (leaves == null) throw new IllegalArgumentException("No leaves!");
}
public void grow() {
validate();
}
}
public abstract class Plant {
private String roots;
private String trunk;
private void validate() {
if (roots == null) throw new IllegalArgumentException("No roots!");
if (trunk == null) throw new IllegalArgumentException("No trunk!");
validateEx();
}
protected void validateEx() { }
public abstract void grow();
}
final
there.final
there.
public class StringUtils // not final to allow subclassing
{
protected StringUtils() {
// prevents calls from subclass
throw new UnsupportedOperationException();
}
public static int count(char c, String s) {
// ...
}
}
public class StringUtils // not final to allow subclassing
{
protected StringUtils() {
// prevents calls from subclass
throw new UnsupportedOperationException();
}
public static int count(char c, String s) {
// ...
}
}
java.io.Serializable
, that do not contain methods orconstants at all.java.io.Serializable
, that do not contain methods orconstants at all.setStackTrace
which changes the exception's stack trace). But, at least, all informationprovided by this exception type is unchangeable.setStackTrace
which changes the exception's stack trace). But, at least, all informationprovided by this exception type is unchangeable.catch(Exception ex)
.4 is the empirical value which is based on reports that we had forthe ThrowsCountCheck over big projects such as OpenJDK.This check also forces developers to put exceptions into a hierarchysuch that in the simplest case, only one type of exception need bechecked for by a caller but any subclasses can be caught specificallyif necessary.For more information on rules for the exceptions andtheir issues, see Effective Java: Programming Language GuideSecond Edition by Joshua Bloch pages 264-273.catch(Exception ex)
.4 is the empirical value which is based on reports that we had forthe ThrowsCountCheck over big projects such as OpenJDK.This check also forces developers to put exceptions into a hierarchysuch that in the simplest case, only one type of exception need bechecked for by a caller but any subclasses can be caught specificallyif necessary. For more information on rules for the exceptions andtheir issues, see Effective Java: Programming Language GuideSecond Edition by Joshua Bloch pages 264-273.protectedAllowed
or packageAllowed
is set."^serialVersionUID$"
by default)."^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 have public accessfor persistent fields, so the default has been changed.protectedAllowed
or packageAllowed
is set."^serialVersionUID$"
by default)."^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.BeforeExecutionExclusionFileFilter
decides which files should beexcluded from being processed by the utility.Exception
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.BeforeExecutionExclusionFileFilter
decides which files should beexcluded from being processed by the utility.Exception
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.SeverityMatchFilter
decidesaudit events according to the severitylevel of the event.SeverityMatchFilter
decidesaudit events according to the severitylevel of the event.SuppressionCommentFilter
usespairs of comments to suppress audit events.SuppressionCommentFilter
usespairs of comments to suppress audit events.<module name="TreeWalker"/>
) and onlyapplies to checks which are also defined within this module.To filter non-TreeWalker checks like RegexpSingleline
,a SuppressWithPlainTextCommentFilter or similar filter must be used.SuppressionFilter
rejectsaudit events for Check errors according toa suppressions XMLdocument in a file. If there is no configuredsuppressions file or the optional is set to true andsuppressions file was not found the Filter accepts all audit events.SuppressionFilter
rejectsaudit events for Check violations according toa suppressions XMLdocument in a file. If there is no configuredsuppressions file or the optional is set to true andsuppressions file was not found the Filter accepts all audit events.SuppressionSingleFilter
suppresses audit events forChecks violations in the specified file, class, checks, message, module id,lines, and columns.SuppressionXpathFilter
works asSuppressionFilter.Additionally, filter processes suppress-xpath
elements,which contains xpath-expressions. Xpath-expressionsare queries for suppressed nodes inside the AST tree.SuppressionXpathSingleFilter
suppresses audit events forChecks violations in the specified file, class, checks, message, module id,and xpath.SuppressWarningsFilter
uses annotations tosuppress audit events.SuppressionCommentFilter
. 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.SuppressWarningsHolder
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.SuppressWarningsFilter
uses annotation{@code SuppressWarnings} to suppress audit events.SuppressionCommentFilter
. 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.SuppressWarningsHolder
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.SuppressWithNearbyCommentFilter
usesindividual comments to suppress audit events.SuppressionCommentFilter
.Whereas the SuppressionCommentFilter uses matched pairs offilters to turn on/off comment matching,SuppressWithNearbyCommentFilter
usessingle comments. This requires fewer lines to mark a region, andmay be aesthetically preferable in some contexts.SuppressWithNearbyCommentFilter
usesnearby comments to suppress audit events.SuppressionCommentFilter
.Whereas the SuppressionCommentFilter uses matched pairs offilters to turn on/off comment matching,SuppressWithNearbyCommentFilter
usessingle comments. This requires fewer lines to mark a region, andmay be aesthetically preferable in some contexts.<module name="TreeWalker"/>
) and onlyapplies to checks which are also defined within this module.To filter non-TreeWalker checks like RegexpSingleline
,a SuppressWithPlainTextCommentFilter or similar filter must be used.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. headerFile
specifies a file that containsthe required header. Alternatively, the header specification can beset directly in the header
propertywithout the need for an external file.ignoreLines
specifies the linenumbers to ignore when matching lines in a header file. Thisproperty is very useful for supporting headers that containcopyright dates. For example, consider the following header:
line 1: ////////////////////////////////////////////////////////////////////
line 2: // checkstyle:
line 3: // Checks Java source code for adherence to a set of rules.
line 4: // Copyright (C) 2002 Oliver Burn
line 5: ////////////////////////////////////////////////////////////////////
ignoreLines
to 4
. headerFile
specifies a file that containsthe required header. Alternatively, the header specification can beset directly in the header
propertywithout the need for an external file.ignoreLines
specifies the linenumbers to ignore when matching lines in a header file. Thisproperty is very useful for supporting headers that containcopyright dates. For example, consider the following header:
line 1: ////////////////////////////////////////////////////////////////////
line 2: // checkstyle:
line 3: // Checks Java source code for adherence to a set of rules.
line 4: // Copyright (C) 2002 Oliver Burn
line 5: ////////////////////////////////////////////////////////////////////
ignoreLines
to 4
.sun.*
packages sinceprograms that contain direct calls to the sun.*
packages are "not guaranteedto work on all Java-compatible platforms". To reject other packages, set property illegalPkgs
to a list of the illegal packages.sun.*
packages sinceprograms that contain direct calls to the sun.*
packages are "notguaranteed to work on all Java-compatible platforms". To reject other packages,set property illegalPkgs
to a list of the illegal packages.
The DTD for a import control XML document is at http://checkstyle.sourceforge.net/dtds/import_control_1_3.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
"-//Puppy Crawl//DTD Import Control 1.3//EN"
"http://checkstyle.sourceforge.net/dtds/import_control_1_3.dtd">
+
Since Checkstyle 4.0
Controls what can be imported in each package and file. Useful forensuring that application layering rules are not violated,especially on large projects.
You can control imports based on the a package name or based on the filename. When controlling packages, all files and sub-packages in the declaredpackage will be controlled by this check. To specify differences between a main packageand a sub-package, you must define the sub-package inside the main package. Whencontrolling file, only the file name is considered and only files processed byTreeWalker. The file's extension is ignored.
Short description of the behaviour:
The DTD for a import control XML document is at https://checkstyle.org/dtds/import_control_1_4.dtd. Itcontains documentation on each of the elements and attributes.
The check validates a XML document when it loads the document.To validate against the above DTD, include the followingdocument type declaration in your XML document:
<!DOCTYPE import-control PUBLIC
"-//Checkstyle//DTD ImportControl Configuration 1.4//EN"
"https://checkstyle.org/dtds/import_control_1_4.dtd">
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.imports com.puppycrawl.tools.checkstyle.checks.imports.ImportOrderCheck: Description: | -Since Checkstyle 3.2
Checks the ordering/grouping of imports. Features are:
Examples section contains examples thatwork with default formatter configurations of Eclipse, IntelliJ IDEA and NetBeans
+
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 @@ -487,31 +529,43 @@ com.puppycrawl.tools.checkstyle.checks.imports.RedundantImportCheck: Package: com.puppycrawl.tools.checkstyle.checks.imports com.puppycrawl.tools.checkstyle.checks.imports.UnusedImportsCheck: Description: | -Since Checkstyle 3.0
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.Date
would beconsidered referenced with the Javadoc comment{@link Date}
. The alternative to avoid introducing acompile time dependency would be to write the Javadoc comment as{@link java.util.Date}
.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 asunused:
+
Since Checkstyle 3.0
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.Date
would beconsidered referenced with the Javadoc comment{@link Date}
. The alternative to avoid introducing acompile time dependency would be to write the Javadoc comment as{@link java.util.Date}
.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:
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.javadoc.AtclauseOrderCheck: Description: | -Since Checkstyle 6.0
Checks the order of javadoc block-tags or javadoc tags.
Note: Google used term "at-clauses" for block tags in his guide till 2017-02-28.
+
Checks the order ofjavadoc block-tags or javadoc tags.
Note: Google used the term "at-clauses" for block tags in their guide till 2017-02-28.
+ 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.InvalidJavadocPositionCheck: + Description: | +Checks that Javadocs are located at the correct position.As specified at Documentation Comment Specification for the Standard Doclet,Javadocs are recognized only when placed immediately before module, package, class,interface, constructor, method, or field declarations. Any other position, likein the body of a method, will be ignored by the javadoc tool and is consideredinvalid by this check.
+ 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.JavadocBlockTagLocationCheck: + Description: | +Checks that ajavadoc block tag appears only at the beginning of a line, ignoringleading asterisks and white space. A block tag is a token that startswith @
symbol and is preceded by a whitespace. This checkignores block tags in comments and inside inline tags {@code } and{@literal }.
Rationale: according tothe specification all javadoc block tags should be placed at thebeginning of a line. Tags that are not placed at the beginning are treatedas plain text. To recognize intentional tag placement to text areait is better to escape the @
symbol, and all non-escapedtags should be located at the beginning of the line. See NOTE sectionfor details on how to escape.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck: Description: | -Since Checkstyle 3.0
Checks the Javadoc of a method or constructor. By default,does not check for unused throws. To allow documentedjava.lang.RuntimeException
s that are notdeclared, set property allowUndeclaredRTE to true. The scopeto verify is specified using the Scope
class anddefaults to Scope.PRIVATE
. To verify anotherscope, set property scope to a differentscope.
Error messages about parameters and type parametersfor which no param tags arepresent can be suppressed by defining propertyallowMissingParamTags
. Error messages aboutexceptions which are declared to be thrown, but for which nothrows tag is present can be suppressed by defining propertyallowMissingThrowsTags
. Error messages aboutmethods which return non-void but for which no return tag ispresent can be suppressed by defining propertyallowMissingReturnTag
.
Javadoc is not required on a method that is tagged with the@Override
annotation. However underJava 5 it is not possible to mark a method required for aninterface (this was corrected under Java 6). HenceCheckstyle supports using the convention of using a single{@inheritDoc}
tag instead of all theother tags.
Note that only inheritable items will allow the{@inheritDoc}
tag to be used in placeof comments. Static methods at all visibilities, private non-staticmethods and constructors are not inheritable.
For example, if the following method isimplementing a method required by an interface, then theJavadoc could be done as:
/** {@inheritDoc} */
public int checkReturnTag(final int aTagIndex,
JavadocTag[] aTags,
int aLineNo)
The classpath may need to be configured to locate the classinformation. The classpath configuration is dependent on themechanism used to invoke Checkstyle.
+
Since Checkstyle 3.0
Checks the Javadoc of a method or constructor. By default,does not check for unused throws. To allow documentedjava.lang.RuntimeException
s that are notdeclared, set property allowUndeclaredRTE to true. The scopeto verify is specified using the Scope
class anddefaults to Scope.PRIVATE
. To verify anotherscope, set property scope to a differentscope.
Violates parameters and type parametersfor which no param tags arepresent can be suppressed by defining propertyallowMissingParamTags
. Violatesexceptions which are declared to be thrown, but for which nothrows tag is present can be suppressed by defining propertyallowMissingThrowsTags
. Violatesmethods which return non-void but for which no return tag ispresent can be suppressed by defining propertyallowMissingReturnTag
.
Javadoc is not required on a method that is tagged with the@Override
annotation. However underJava 5 it is not possible to mark a method required for aninterface (this was corrected under Java 6). HenceCheckstyle supports using the convention of using a single{@inheritDoc}
tag instead of all theother tags.
Note that only inheritable items will allow the{@inheritDoc}
tag to be used in placeof comments. Static methods at all visibilities, private non-staticmethods and constructors are not inheritable.
For example, if the following method isimplementing a method required by an interface, then theJavadoc could be done as:
/** {@inheritDoc} */
public int checkReturnTag(final int aTagIndex,
JavadocTag[] aTags,
int aLineNo)
The classpath may need to be configured to locate the classinformation. The classpath configuration is dependent on themechanism used to invoke Checkstyle.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocPackageCheck: Description: | -Since Checkstyle 5.0
Checks that each Java package has a Javadoc file used forcommenting. By default it only allows a package-info.java
file, but can beconfigured to allow a package.html
file.
An error will be reported if both files exist as this is notallowed by the Javadoc tool.
+
Since Checkstyle 5.0
Checks that each Java package has a Javadoc file used forcommenting. By default it only allows a package-info.java
file, but can beconfigured to allow a package.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 com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocParagraphCheck: Description: | -Since Checkstyle 6.0
Checks that:
+
Since Checkstyle 6.0
Checks that:
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.javadoc @@ -539,6 +593,24 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocVariableCheck: This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project. Package: com.puppycrawl.tools.checkstyle.checks.javadoc +com.puppycrawl.tools.checkstyle.checks.javadoc.MissingJavadocMethodCheck: + Description: | +Checks for missing Javadoc comments for a method or constructor.The scope to verify is specified using the Scope
class anddefaults to Scope.PUBLIC
. To verify anotherscope, set property scope to a differentscope.
Javadoc is not required on a method that is tagged with the@Override
annotation. However underJava 5 it is not possible to mark a method required for aninterface (this was corrected under Java 6). HenceCheckstyle supports using the convention of using a single{@inheritDoc}
tag instead of all theother tags.
For getters and setters for the property allowMissingPropertyJavadoc
,the methods must match exactly the structures below.
public void setNumber(final int number)
{
mNumber = number;
}
public int getNumber()
{
return mNumber;
}
public boolean isSomething()
{
return false;
}
+ 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.
+ 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.MissingJavadocTypeCheck: + Description: | +Checks for missing Javadoc comments for class, enum, interface, and annotationinterface definitions. The scope to verify is specified using the Scope
class and defaults to Scope.PUBLIC
. To verifyanother scope, set property scope to one of theScope
constants.
+ 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.NonEmptyAtclauseDescriptionCheck: Description: |Since Checkstyle 6.0
Checks that the at-clause tag is followed by description.
@@ -553,31 +625,31 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.SingleLineJavadocCheck: Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.SummaryJavadocCheck: Description: | -
Since Checkstyle 6.0
Checks that Javadoc summary sentence does not contain phrases that are not recommended to use. Summaries that containonly the {@inheritDoc}
tag are skipped. Check also violate javadoc that does not contain first sentence.
+
Since Checkstyle 6.0
Checks that Javadoc summary sentence does not contain phrases that are not recommended to use.Summaries that contain only the {@inheritDoc}
tag are skipped. Check alsoviolate javadoc that does not contain first sentence.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.javadoc.WriteTagCheck: Description: | -Since Checkstyle 4.2
Requires user defined JavaDoc tag to be present in javadoc comment with defined format. To define theformat for a tag, set property tagFormat to a regularexpression. Property tagSeverity is used for severity of events when the tag exists.
+
Since Checkstyle 4.2
Requires user defined JavaDoc tag to be present in javadoc comment withdefined format. To define the format for a tag, set property tagFormat to a regularexpression. Property tagSeverity is used for severity of events when the tag exists.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.javadoc com.puppycrawl.tools.checkstyle.checks.metrics.BooleanExpressionComplexityCheck: Description: | -Since Checkstyle 3.4
Restrict the number of number of &&
, ||
,&
, |
and ^
in an expression.
Rationale: Too many conditions leads to code that is difficultto read and hence debug and maintain.
Note that the operators &
and|
are not only integer bitwise operators, they are also thenon-shortcut versions of the boolean operators.&&
and ||
.
Note that &
, |
and ^
are not checkedif they are part of constructor or method callbecause they can be applied to non boolean variables andCheckstyle does not know types of methods from different classes.
+
Since Checkstyle 3.4
Restrict the number of number of &&
, ||
,&
, |
and ^
in an expression.
Rationale: Too many conditions leads to code that is difficultto read and hence debug and maintain.
Note that the operators &
and|
are not only integer bitwise operators, they are also thenon-shortcut versions of the boolean operators.&&
and ||
.
Note that &
, |
and ^
are not checkedif they are part of constructor or method callbecause they can be applied to non boolean variables andCheckstyle does not know types of methods from different classes.
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: | -Since Checkstyle 3.4
This metric measures the number of instantiations of otherclasses within the given class. This type of coupling is notcaused by inheritance or the object orientedparadigm. Generally speaking, any data type with other datatypes as members or local variable that is an instantiation(object) of another class has data abstraction coupling (DAC).The higher the DAC, the more complex the structure of the class.
This check processes files in the following way:
import java.math.BigDecimal
),or the class was referenced with the package name (i.e. java.math.BigDecimal value
)and the package was added to the excludedPackages
parameter,the class does not increase complexity.excludedClasses
parameter,the class does not increase complexity.+
Since Checkstyle 3.4
This metric measures the number of instantiations of otherclasses within the given class. This type of coupling is notcaused by inheritance or the object orientedparadigm. Generally speaking, any data type with other datatypes as members or local variable that is an instantiation(object) of another class has data abstraction coupling (DAC).The higher the DAC, the more complex the structure of the class.
This check processes files in the following way:
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: | -Since Checkstyle 3.4
The number of other classes a given class relies on. Also thesquare of this has been shown to indicate the amount ofmaintenance required in functional programs (on a file basis)at least.
This check processes files in the following way:
import java.math.BigDecimal
),or the class was referenced with the package name (i.e. java.math.BigDecimal value
)and the package was added to the excludedPackages
parameter,the class does not increase complexity.excludedClasses
parameter,the class does not increase complexity.+
Since Checkstyle 3.4
The number of other classes a given class relies on. Also thesquare of this has been shown to indicate the amount ofmaintenance required in functional programs (on a file basis)at least.
This check processes files in the following way:
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 @@ -595,200 +667,224 @@ com.puppycrawl.tools.checkstyle.checks.metrics.JavaNCSSCheck: Package: com.puppycrawl.tools.checkstyle.checks.metrics com.puppycrawl.tools.checkstyle.checks.metrics.NPathComplexityCheck: Description: | -Since Checkstyle 3.4
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 a function(method).
Metric was described at "NPATH: a measure of execution pathcomplexity and its applications". If you need detailed description of algorithm, please read that article,it is well written and have number of examples and details.
Here is some quotes:
An NPATH threshold value of 200 has been 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 high count of 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. No operators - 0 |
continue | 1 |
return | 1 |
Statement (even sequential statements) | 1 |
Empty block {} | 1 |
Function call | 1 |
Function(Method) declaration or Block | P(i=1:i=N)NP(Statement[i]) |
Rationale: Nejmeh says that his group had an informal 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.
+
Since Checkstyle 3.4
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 high count ofand (&&) 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: | -Since Checkstyle 3.1
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[])
+
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 com.puppycrawl.tools.checkstyle.checks.AvoidEscapedUnicodeCharactersCheck: Description: | -Since Checkstyle 5.8
Restrict using Unicode escapes (e.g. \u221e).It is possible to allow using escapes for non-printable(control) characters.Also, this check can be configured to allow using escapesif trail comment is present. By the option it is possible toallow using escapes if literal contains only them.
+
Restrict usingUnicode escapes (such as \u221e).It is possible to allow using escapes fornon-printable, control characters.Also, this check can be configured to allow using escapesif trail comment is present. By the option it is possible toallow using escapes if literal contains only them.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.indentation.CommentsIndentationCheck: Description: | -Since Checkstyle 6.10
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 found here
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
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.
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: | -Since Checkstyle 3.2
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 com.puppycrawl.tools.checkstyle.checks.FinalParametersCheck: Description: | -Since Checkstyle 3.0
Check that parameters for methods, constructors, and catch blocks arefinal. Interface, abstract, and native methods are not checked: the finalkeyword does not make sense for interface, abstract, and native methodparameters as there is no code that could modify the parameter.
Rationale: Changing the value of parameters during the execution ofthe method's algorithm can be confusing and should be avoided. Agreat way to let the Java compiler prevent this coding style is todeclare parameters final.
+
Check that parameters for methods, constructors, catch and for-each blocks arefinal. Interface, abstract, and native methods are not checked: the finalkeyword does not make sense for interface, abstract, and native methodparameters as there is no code that could modify the parameter.
Rationale: Changing the value of parameters during the execution ofthe method's algorithm can be confusing and should be avoided. Agreat way to let the Java compiler prevent this coding style is todeclare parameters final.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck: Description: | -Since Checkstyle 3.1
Checks correct indentation of Java code.
The idea behind this is that while pretty printers aresometimes convenient for bulk reformats of legacy code, they ofteneither aren't configurable enough or just can't anticipate howformat should be done. Sometimes this is personal preference, othertimes it is practical experience. In any case, this check shouldjust ensure that a minimal set of indentation rules is followed.
+
Checks correct indentation of Java code.
The idea behind this is that while pretty printers aresometimes convenient for bulk reformats of legacy code, they ofteneither aren't configurable enough or just can't anticipate howformat should be done. Sometimes this is personal preference, othertimes it is practical experience. In any case, this check shouldjust ensure that a minimal set of indentation rules is followed.
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.NewlineAtEndOfFileCheck: Description: | -Since Checkstyle 3.1
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):
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 property for atChecker.Please make sure required file extensions are mentioned at Checker's fileExtensions property.
+
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.
+ 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.
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.OuterTypeFilenameCheck: Description: | -Since Checkstyle 5.3
Checks that the outer type name and the file name match. For example,the class Foo
must be in a file namedFoo.java
.
+
Checks that the outer type name and the file name match. For example,the class Foo
must be in a file namedFoo.java
.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.TodoCommentCheck: Description: | -Since Checkstyle 3.0
A check for TODO:
comments. Actuallyit is a generic regularexpression matcher on Java comments. To check for otherpatterns in Java comments, set the format
property.
+
A check for TODO:
comments. Actuallyit is a genericregularexpression matcher on Java comments. To check for otherpatterns in Java comments, set the format
property.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.TrailingCommentCheck: Description: | -Since Checkstyle 3.4
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:
McConnel'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 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.
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.TranslationCheck: Description: | -Since Checkstyle 3.0
A FileSetCheck that ensuresthe correct translation of code by checking property files forconsistency regarding their keys. Two property filesdescribing one and the same context are consistent if theycontain the same keys. TranslationCheck also can check an existence of requiredtranslations which must exist in project, if 'requiredTranslations' option is used.
Consider the following properties file in the same directory:
The Translation check will find the typo in the German hello
key, the missing ok
key in the default resource file and themissing cancel
key in the German resource file:
Attention: this Check could produce false-positives if it is used withChecker that use cache (property "cacheFile")This is known design problem, will be addressed atissue.
+
A FileSetCheck that ensuresthe correct translation of code by checking property files forconsistency regarding their keys. Two property filesdescribing one and the same context are consistent if theycontain the same keys. TranslationCheck also can check an existence of requiredtranslations which must exist in project, if requiredTranslations
option is used.
Consider the following properties file in the same directory:
The Translation check will find the typo in the German hello
key, the missing ok
key in the default resource file and themissing cancel
key in the German resource 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 com.puppycrawl.tools.checkstyle.checks.UncommentedMainCheck: Description: | -Since Checkstyle 3.2
Checks for uncommented main() methods.
Rationale: A main() method is often used for debuggingpurposes. When debugging is finished, developers often forgetto remove the method, which changes the API and increases thesize of the resulting class or JAR file. With the exception ofthe real program entry points, all main() methods should beremoved or commented out of the sources.
+
Checks for uncommented main() methods.
Rationale: A main() method is often used for debuggingpurposes. When debugging is finished, developers often forgetto remove the method, which changes the API and increases thesize of the resulting class or JAR file. With the exception ofthe real program entry points, all main() methods should beremoved or commented out of the sources.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks com.puppycrawl.tools.checkstyle.checks.UniquePropertiesCheck: Description: | -Since Checkstyle 5.7
Checks properties files for duplicated properties.
Rationale: Multiple property keys usually appear after mergeor rebase of several branches. While there are no errors inruntime, there can be a confusion due to having different valuesfor the duplicated properties.
+
Checks properties files for duplicate property keys.
Rationale: Multiple property keys usually appear after mergeor rebase of several branches. While there are no problems inruntime, there can be a confusion due to having different valuesfor the duplicated properties.
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.UpperEllCheck: Description: | -Since Checkstyle 3.0
Checks that long constants are defined with an upper ell. Thatis ' L'
and not 'l'
. This is in accordance with the JavaLanguage Specification, Section 3.10.1.
The capital L looks a lot like 1
.
+
Checks that long constants are defined with an upper ell. Thatis 'L'
and not 'l'
. This is in accordance with the JavaLanguage Specification,Section 3.10.1.
Rationale: The lower-case ell 'l'
looks a lot like 1
.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks +com.puppycrawl.tools.checkstyle.checks.modifier.ClassMemberImpliedModifierCheck: + Description: | +Checks for implicit modifiers on nested types in classes.
This check is effectively the opposite ofRedundantModifier.It checks the modifiers on nested types in classes, ensuring that certainmodifiers are explicitly specified even though they are actually redundant.
Nested enums and interfaces within a class are always static
and as such thecompiler does not require the static
modifier. This check provides theability to enforce that the static
modifier is explicitly coded and notimplicitly added by the compiler.
Rationale for this check:Nested enums and interfaces are treated differently from nested classes as they areonly allowed to be static
. Developers should not need to remember this rule,and this check provides the means to enforce that the modifier is coded explicitly.
+ 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.InterfaceMemberImpliedModifierCheck: + Description: | +Checks for implicit modifiers on interface members and nested types.
This check is effectively the opposite ofRedundantModifier.It checks the modifiers on interface members, ensuring that certainmodifiers are explicitly specified even though they are actually redundant.
Methods in interfaces are public
by default, however from Java 9they can also be private
. This check provides the ability to enforcethat public
is explicitly coded and not implicitly added by the compiler.
From Java 8, there are three types of methods in interfaces - static methodsmarked with static
, default methods marked with default
andabstract methods which do not have to be marked with anything.From Java 9, there are also private methods marked with private
.This check provides the ability to enforce that abstract
is explicitlycoded and not implicitly added by the compiler.
Fields in interfaces are always public static final
and as such thecompiler does not require these modifiers. This check provides the ability toenforce that these modifiers are explicitly coded and not implicitly added bythe compiler.
Nested types within an interface are always public static
and as such thecompiler does not require the public static
modifiers. This check providesthe ability to enforce that the public
and static
modifiersare explicitly coded and not implicitly added by the compiler.
Rationale for this check:Methods, fields and nested types are treated differently depending on whetherthey are part of an interface or part of a class. For example, by default methodsare package-scoped on classes, but public in interfaces. However, from Java 8 onwards,interfaces have changed to be much more like abstract classes.Interfaces now have static and instance methods with code. Developers should not haveto remember which modifiers are required and which are implied.This check allows the simpler alternative approach to be adopted where theimplied modifiers must always be coded explicitly.
+ 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.ModifierOrderCheck: Description: | -Since Checkstyle 3.0
Checks that the order of modifiers conforms to the suggestions inthe JavaLanguage specification, sections 8.1.1, 8.3.1, 8.4.3 and 9.4. The correct order is:
public
protected
private
abstract
default
static
final
transient
volatile
synchronized
native
strictfp
ATTENTION: We skip type annotations from validation.
+
Since Checkstyle 3.0
Checks that the order of modifiers conforms to the suggestions inthe JavaLanguage specification, sections 8.1.1, 8.3.1, 8.4.3 and 9.4. The correct order is:
public
protected
private
abstract
default
static
final
transient
volatile
synchronized
native
strictfp
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: | -Since Checkstyle 3.0
Checks for redundant modifiers in:
interface
declarations that are declaredas static
.enum
definitions that are declaredas static
.Rationale: The Java Language Specification stronglydiscourages the usage of public
and abstract
for methoddeclarations in interface definitions as a matter of style.
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 the declaredenumeration 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:
+
Since Checkstyle 3.0
Checks for redundant modifiers in:
interface
declarations that are declaredas static
.enum
definitions that are declaredas static
.Rationale: The Java Language Specification stronglydiscourages the usage of public
and abstract
for methoddeclarations in interface definitions as a matter of style.
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:
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: | -Since Checkstyle 5.8
The Check validate abbreviations(consecutive capital letters)length in identifier name, it also allows to enforce camel case naming. Please read more atGoogle Style Guideto get to know how to avoid long abbreviations in names.
allowedAbbreviationLength specifies how many consecutive capital letters areallowed in the identifier.A value of 3 indicates that up to 4 consecutive capital letters are allowed,one after the other, before a violation is printed. The identifier 'MyTEST' would beallowed, but 'MyTESTS' would not be.A value of 0 indicates that only 1 consecutive capital letter is allowed. Thisis what should be used to enforce strict camel casing. The identifier 'MyTest' wouldbe allowed, but 'MyTEst' would not be.
+
The Check validate abbreviations(consecutive capital letters)length in identifier name, it also allows to enforce camel case naming. Please read more atGoogle Style Guideto get to know how to avoid long abbreviations in names.
allowedAbbreviationLength
specifies how many consecutive capital letters areallowed in the identifier.A value of 3 indicates that up to 4 consecutive capital letters are allowed,one after the other, before a violation is printed. The identifier 'MyTEST' would beallowed, but 'MyTESTS' would not be.A value of 0 indicates that only 1 consecutive capital letter is allowed. Thisis what should be used to enforce strict camel casing. The identifier 'MyTest' wouldbe allowed, but 'MyTEst' would not be.
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: | -Since Checkstyle 3.2
Validates identifiers for abstract
classes.
+
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.
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
.CatchParameterNameCheck": Description: | -Since Checkstyle 6.14
Checks that catch parameter names conform to a format specified by the format property.Default pattern has the following characteristic:
e
abbreviation (suitable for exceptions end errors)ex
abbreviation (suitable for exceptions)t
abbreviation (suitable for throwables)e1
or t2
pException
ie
or ee
+
Checks that catch
parameter names conform to a format specified by theformat property.
Default pattern has the following characteristic:
e
abbreviation (suitable for exceptions end errors)ex
abbreviation (suitable for exceptions)t
abbreviation (suitable for throwables)e1
or t2
pException
ie
or ee
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: "com.puppycrawl.tools.checkstyle.checks.naming
" com.puppycrawl.tools.checkstyle.checks.naming.ClassTypeParameterNameCheck: Description: | -Since Checkstyle 5.0
Validates identifiers for class type parameters.
+
Checks that class type parameter names conform to a format specified by the formatproperty.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.naming com.puppycrawl.tools.checkstyle.checks.naming.ConstantNameCheck: Description: | -Since Checkstyle 3.0
Validates identifiers for constants (static
, final
fields).
+
Checks that constant names conform to a format specified by the format property.A constant is a static and final field or aninterface/annotation field, except serialVersionUID andserialPersistentFields.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.naming com.puppycrawl.tools.checkstyle.checks.naming.InterfaceTypeParameterNameCheck: Description: | -Since Checkstyle 5.8
Validates identifiers for interface type parameters.
+
Checks that interface type parameter names conform to a format specified by the formatproperty.
+ This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project. +
+ Package: com.puppycrawl.tools.checkstyle.checks.naming +com.puppycrawl.tools.checkstyle.checks.naming.LambdaParameterNameCheck: + Description: | +Check to verify lambda parameter names.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.naming com.puppycrawl.tools.checkstyle.checks.naming.LocalFinalVariableNameCheck: Description: | -Since Checkstyle 3.0
Validates identifiers for local, final
variables, includingcatch
parameters and resources in try
statements.
+
Checks that local final variable names conform to a format specifiedby the format property. A catch parameter and resources in try statementsare considered to be a local, final variables.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.naming com.puppycrawl.tools.checkstyle.checks.naming.LocalVariableNameCheck: Description: | -Since Checkstyle 3.0
Checks that local, non-final
variable names conform to a format specifiedby the format property.
+
Checks that local, non-final
variable names conform to a format specifiedby the format property. A catch parameter is considered to be a local variable.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.naming com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck: Description: | -Since Checkstyle 3.0
Validates identifiers for non-static
fields.
+
Checks that instance variable names conform to a format specified by 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.naming com.puppycrawl.tools.checkstyle.checks.naming.MethodNameCheck: Description: | -Since Checkstyle 3.0
Validates identifiers for methods.
+
Checks that method names conform to a format specified by the format property.
Also, checks if a method name has the same name as the residing class.The default is false (it is not allowed). It is legal in Java to havemethod with the same name as a class. As long as a return type is specifiedit is a method and not a constructor which it could be easily confused as.Does not check-style the name of an overridden methods because the developerdoes not have a choice in renaming such methods.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.naming com.puppycrawl.tools.checkstyle.checks.naming.MethodTypeParameterNameCheck: Description: | -Since Checkstyle 5.0
Validates identifiers for method type parameters.
+
Checks that method type parameter names conform to a format specified by the formatproperty.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.naming com.puppycrawl.tools.checkstyle.checks.naming.PackageNameCheck: Description: | -Since Checkstyle 3.0
Validates identifiers for packages.
+
Checks that package names conform to a format specified by the format property.
The default value of format
for module PackageName
has beenchosen to match the requirements in the JavaLanguage specification and the Sun coding conventions. Howeverboth underscores and uppercase letters are rather uncommon, so mostconfigurations should probably assign value ^[a-z]+(\.[a-z][a-z0-9]*)*$
toformat
for module PackageName
.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.naming com.puppycrawl.tools.checkstyle.checks.naming.ParameterNameCheck: Description: | -Since Checkstyle 3.0
Checks that method and catch
parameter names conform to a format specifiedby the format property. By using accessModifiers
property it is possibleto specify different formats for methods at different visibility levels.
+
Checks that method parameter names conform to a format specifiedby the format property. By using accessModifiers
property it is possibleto specify different formats for methods at different visibility levels.
To validate catch
parameters please useCatchParameterName.
To validate lambda parameters please useLambdaParameterName.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.naming com.puppycrawl.tools.checkstyle.checks.naming.StaticVariableNameCheck: Description: | -Since Checkstyle 3.0
Validates identifiers for static
, non-final
fields.
+
Checks that {@code static}, non-{@code final} variable names conform to a formatspecified by 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.naming com.puppycrawl.tools.checkstyle.checks.naming.TypeNameCheck: Description: | -Since Checkstyle 3.0
Validates identifiers for classes, interfaces, enums, and annotations.
+
Checks that type names for classes, interfaces, enums, and annotations conform to aformat specified by 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.naming com.puppycrawl.tools.checkstyle.checks.regexp.RegexpCheck: Description: | -Since Checkstyle 4.0
A check that makes sure that a specified pattern exists, exists lessthan a set number of times, or does not exist in the file.
This check combines all the functionality provided byRegexpHeaderexcept supplying the regular expression from a file.
It differs from them in that it works in multiline mode.Its regular expression can span multiple lines and it checks thisagainst the whole file at once.The others work in singleline mode.Their single or multiple regular expressions can only span one line.They check each of these against each line in the file in turn.
Note: Because of the different mode of operation there may besome changes in the regular expressions used to achieve a particular end.
In multiline mode...
^
means the beginning of a line, as opposed to beginning of the input.\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 the java.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.
+
Since Checkstyle 4.0
A check that makes sure that a specified pattern exists, exists lessthan a set number of times, or does not exist in the file.
This check combines all the functionality provided byRegexpHeaderexcept supplying the regular expression from a file.
It differs from them in that it works in multiline mode.Its regular expression can span multiple lines and it checks thisagainst the whole file at once.The others work in singleline mode.Their single or multiple regular expressions can only span one line.They check each of these against each line in the file in turn.
Note: Because of the different mode of operation there may besome changes in the regular expressions used to achieve a particular end.
In multiline mode...
^
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 @@ -800,7 +896,7 @@ com.puppycrawl.tools.checkstyle.checks.regexp.RegexpMultilineCheck: Package: com.puppycrawl.tools.checkstyle.checks.regexp com.puppycrawl.tools.checkstyle.checks.regexp.RegexpOnFilenameCheck: Description: | -Since Checkstyle 6.15
Implementation of a check that looks for a file name and/or path match (or mis-match)against specified patterns. It can also be used to verify files match specific namingpatterns not covered by other checks (Ex: properties, xml, etc.).
When customizing the check, the properties are applied in a specific order.The fileExtensions property first picks only files that match any of thespecific extensions supplied.Once files are matched against the fileExtensions, the match property is thenused in conjunction with the patterns to determine if the check is lookingfor a match or mis-match on those files. If the fileNamePattern issupplied, the matching is only applied to the fileNamePattern and not thefolderPattern. If no fileNamePattern is supplied, then matching is appliedto the folderPattern only and will result in all files in a folder to bereported on violations. If no folderPattern is supplied, then all foldersthat checkstyle finds are examined for violations.The ignoreFileNameExtensions property drops the file extension and appliesthe fileNamePattern only to the rest of file name. For example, if the file isnamed 'test.java' and this property is turned on, the pattern is only appliedto 'test'.
If this check is configured with no properties, then the default behaviorof this check is to report file names with spaces in them.When at least one pattern property is supplied, the entire check is underthe user's control to allow them to fully customize the behavior.
It is recommended that if you create your own pattern, to alsospecify a custom error message. This allows the error 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 error messages.
+
Since Checkstyle 6.15
Implementation of a check that looks for a file name and/or path match (or mis-match)against specified patterns. It can also be used to verify files match specific namingpatterns not covered by other checks (Ex: properties, xml, etc.).
When customizing the check, the properties are applied in a specific order.The fileExtensions property first picks only files that match any of thespecific extensions supplied.Once files are matched against the fileExtensions, the match property is thenused in conjunction with the patterns to determine if the check is lookingfor a match or mis-match on those files. If the fileNamePattern issupplied, the matching is only applied to the fileNamePattern and not thefolderPattern. If no fileNamePattern is supplied, then matching is appliedto the folderPattern only and will result in all files in a folder to bereported on violations. If no folderPattern is supplied, then all foldersthat checkstyle finds are examined for violations.The ignoreFileNameExtensions property drops the file extension and appliesthe fileNamePattern only to the rest of file name. For example, if the file isnamed 'test.java' and this property is turned on, the pattern is only appliedto 'test'.
If this check is configured with no properties, then the default behaviorof this check is to report file names with spaces in them.When at least one pattern property is supplied, the entire check is underthe user's control to allow them to fully customize the behavior.
It is recommended that if you create your own pattern, to alsospecify a custom violation message. This allows the violation message printedto be clear what the violation is, especially if multiple RegexpOnFilenamechecks are used.Argument 0 for the message populates the check's folderPattern.Argument 1 for the message populates the check's fileNamePattern.The file name is not passed as an argument since it is part of CheckStyle'sdefault violation messages.
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 @@ -812,154 +908,155 @@ com.puppycrawl.tools.checkstyle.checks.regexp.RegexpSinglelineCheck: Package: com.puppycrawl.tools.checkstyle.checks.regexp com.puppycrawl.tools.checkstyle.checks.regexp.RegexpSinglelineJavaCheck: Description: | -Since Checkstyle 6.0
This class is variation on RegexpSingleline for detectingsingle lines that match a supplied regular expression in Java files. It supports suppressing matches in Java comments.
+
Since Checkstyle 6.0
This class is variation on RegexpSingleline 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 ".Caching SupportCheck": {} ".Localisation SupportCheck": {} ".Base directory supportCheck": {} +".Enable External DTD loadCheck": {} com.puppycrawl.tools.checkstyle.checks.sizes.AnonInnerLengthCheck: Description: | -Since Checkstyle 3.2
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 com.puppycrawl.tools.checkstyle.checks.sizes.ExecutableStatementCountCheck: Description: | -Since Checkstyle 3.2
Restricts the number of executable statements to a specified limit.
+
Restricts the number of executable statements to a specified limit.
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.FileLengthCheck: Description: | -Since Checkstyle 5.0
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.LineLengthCheck: Description: | -Since Checkstyle 3.0
Checks for long lines.
Rationale: Long lines are hard to read in printouts or if developershave limited screen space for the source code, e.g. if the IDEdisplays additional information like project tree, class hierarchy,etc.
+
Checks for long lines.
Rationale: Long lines are hard to read in printouts or if developershave limited screen space for the source code, e.g. if the IDEdisplays additional information like project tree, class hierarchy,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.sizes com.puppycrawl.tools.checkstyle.checks.sizes.MethodCountCheck: Description: | -Since Checkstyle 5.3
Checks the number of methods declared in each type declaration by access modifier ortotal count.
This check can be configured to flag classes that define too many methods to prevent theclass from getting too complex.Counting can be customized to prevent too many total methods in a type definition(maxTotal
), or to prevent too many methods of a specific access modifier(private
, package
, protected
orpublic
).Each count is completely separated to customize how many methods of each you want to allow.For example, specifying a maxTotal
of 10, still means you can prevent morethan 0 maxPackage
methods. A violation won't appear for 8 public methods,but one will appear if there is also 3 private methods or any package-private methods.
Methods defined in anonymous classes are not counted towards any totals.Counts only go towards the main type declaration parent, and are kept separate from it'schildren's inner types.
+
Checks the number of methods declared in each type declaration by access modifier ortotal count.
This check can be configured to flag classes that define too many methods to prevent theclass from getting too complex.Counting can be customized to prevent too many total methods in a type definition(maxTotal
), or to prevent too many methods of a specific access modifier(private
, package
, protected
orpublic
).Each count is completely separated to customize how many methods of each you want toallow. For example, specifying a maxTotal
of 10, still means you canprevent more than 0 maxPackage
methods. A violation won't appear for 8public methods, but one will appear if there is also 3 private methods or anypackage-private methods.
Methods defined in anonymous classes are not counted towards any totals.Counts only go towards the main type declaration parent, and are kept separate from it'schildren's inner types.
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.MethodLengthCheck: Description: | -Since Checkstyle 3.0
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 com.puppycrawl.tools.checkstyle.checks.sizes.OuterTypeNumberCheck: Description: | -Since Checkstyle 5.0
Checks for the number of types declared at the outer(or root) level in a file.
Rationale: It is considered good practice to only define one outertype per file.
+
Checks for the number of types declared at the outer(or root) level in a file.
Rationale: It is considered good practice to only define one outertype per 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.sizes com.puppycrawl.tools.checkstyle.checks.sizes.ParameterNumberCheck: Description: | -Since Checkstyle 3.0
Checks the number of parameters of a method or constructor.
+
Checks the number of parameters of a method or constructor.
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.whitespace.EmptyForInitializerPadCheck: Description: | -Since Checkstyle 3.4
Checks the padding of an empty for initializer; that is whetherwhite space is required at an empty for initializer, or such whitespace is forbidden. No check occurs if there is a line wrap at theinitializer, as in
+
Checks the padding of an empty for initializer; that is whetherwhite space is required at an empty for initializer, or such whitespace is forbidden. No check occurs if there is a line wrap at theinitializer, as in
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.whitespace com.puppycrawl.tools.checkstyle.checks.whitespace.EmptyForIteratorPadCheck: Description: | -Since Checkstyle 3.0
Checks the padding of an empty for iterator; that is whether whitespace is required at an empty for iterator, or such white space isforbidden. No check occurs if there is a line wrap at the iterator,as in
+
Checks the padding of an empty for iterator; that is whether a whitespace is required at an empty for iterator, or such white spaces areforbidden. No check occurs if there is a line wrap at the iterator,as in
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.whitespace com.puppycrawl.tools.checkstyle.checks.whitespace.EmptyLineSeparatorCheck: Description: | -Since Checkstyle 5.8
Checks for empty line separators after header, package, all import declarations,fields, constructors, methods, nested classes,static initializers and instance initializers.
ATTENTION: empty line separator is required between AST siblings, not after line where token is found.
+
Checks for empty line separators after header, package, all import declarations,fields, constructors, methods, nested classes,static initializers and instance initializers.
ATTENTION: empty line separator is required between AST siblings,not after line where token is found.
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.FileTabCharacterCheck: Description: | -Since Checkstyle 5.0
Checks that there are no tab characters ('\t'
) in the source code.
Rationale:
+
Checks that there are no tab characters ('\t'
) in the source code.
Rationale:
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.GenericWhitespaceCheck: Description: | -Since Checkstyle 5.0
Checks that the whitespace around the Generic tokens (angle brackets)"<" and ">" are correct to the typical convention.The convention is not configurable.
Left angle bracket ("<"):
Right angle bracket (">"):
Examples with correct spacing:
+
Checks that the whitespace around the Generic tokens (angle brackets)"<" and ">" are correct to the typical convention.The convention is not configurable.
Left angle bracket ("<"):
Right angle bracket (">"):
Examples with correct spacing:
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.MethodParamPadCheck: Description: | -Since Checkstyle 3.4
Checks the padding between the identifier of a method definition,constructor definition, method call, or constructor invocation; andthe left parenthesis of the parameter list. That is, if theidentifier and left parenthesis are on the same line, checks whethera space is required immediately after the identifier or such a spaceis forbidden. If they are not on the same line, reports an error,unless configured to allow line breaks. To allow linebreaks afterthe identifier, set property allowLineBreaks
to true
.
+
Checks the padding between the identifier of a method definition,constructor definition, method call, or constructor invocation; andthe left parenthesis of the parameter list. That is, if theidentifier and left parenthesis are on the same line, checks whethera space is required immediately after the identifier or such a spaceis forbidden. If they are not on the same line, reports a violation,unless configured to allow line breaks. To allow linebreaks afterthe identifier, set property allowLineBreaks
to true
.
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.NoLineWrapCheck: Description: | -Since Checkstyle 5.8
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: | -Since Checkstyle 3.0
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.
+
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.
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: | -Since Checkstyle 3.0
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 property allowLineBreaks
to true
.
+
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.
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.OperatorWrapCheck: Description: | -Since Checkstyle 3.0
Checks the policy on how to wrap lines on operators.
+
Checks the policy on how to wrap lines on operators.
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.ParenPadCheck: Description: | -Since Checkstyle 3.0
Checks the policy on the padding of parentheses; i.e. whether aspace is required after a left parenthesis and before a rightparenthesis, or such spaces are forbidden, with the exception that it doesnot check for padding of the right parenthesis at an empty for iterator andempty for initializer.Use Check EmptyForIteratorPadto validate empty for iterators and EmptyForInitializerPadto validate empty for initializers. Typecasts are also not checked, as there is TypecastParenPadto validate them.
+
Checks the policy on the padding of parentheses; i.e. whether aspace is required after a left parenthesis and before a rightparenthesis, or such spaces are forbidden. No check occurs atthe right parenthesis after an empty for iterator, at the leftparenthesis before an empty for initialization, or at the rightparenthesis of a try-with-resources resource specification wherethe last resource variable has a trailing semi-colon.Use Check EmptyForIteratorPad to validate empty for iterators andEmptyForInitializerPad to validate empty for initializers.Typecasts are also not checked, as there isTypecastParenPad to validate them.
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.SeparatorWrapCheck: Description: | -Since Checkstyle 5.8
Checks line wrapping with separators.
+
Checks line wrapping with separators.
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.SingleSpaceSeparatorCheck: Description: | -Since Checkstyle 6.19
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 com.puppycrawl.tools.checkstyle.checks.whitespace.TypecastParenPadCheck: Description: | -Since Checkstyle 3.2
Checks the policy on the padding of parentheses for typecasts. Thatis, whether a space is required after a left parenthesis and beforea right parenthesis, or such spaces are forbidden.
+
Checks the policy on the padding of parentheses for typecasts. Thatis, whether a space is required after a left parenthesis and beforea right parenthesis, or such spaces are forbidden.
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.WhitespaceAfterCheck: Description: | -Since Checkstyle 3.0
Checks that a token is followed by whitespace.
+
Checks that a token is followed by whitespace, with the exception that itdoes not check for whitespace after the semicolon of an empty for iterator. Use CheckEmptyForIteratorPad to validate empty for iterators.
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.WhitespaceAroundCheck: Description: | -Since Checkstyle 3.0
Checks that a token is surrounded by whitespace. Empty constructor,method, class, enum, interface, loop bodies (blocks), lambdas of the form
may optionally be exempted from the policy using the allowEmptyMethods
, allowEmptyConstructors
, allowEmptyTypes
, allowEmptyLoops
allowEmptyLambdas
and allowEmptyCatches
properties.
This check does not flag as violation double brace initialization like:
new Properties() {{
setProperty("key", "value");
}};
Parameter allowEmptyCatches allows to suppress violations when tokenlist contains SLIST to check if beginning of block is surrounded bywhitespace and catch block is empty, for example:
try {
k = 5 / i;
} catch (ArithmeticException ex) {}
With this property turned off, this raises violation because the beginning of thecatch block (left curly bracket) is not separated from the end of the catchblock (right curly bracket).+
Checks that a token is surrounded by whitespace. Empty constructor,method, class, enum, interface, loop bodies (blocks), lambdas of the form
may optionally be exempted from the policy using the allowEmptyMethods
, allowEmptyConstructors
, allowEmptyTypes
, allowEmptyLoops
,allowEmptyLambdas
and allowEmptyCatches
properties.
This check does not flag as violation double brace initialization like:
new Properties() {{
setProperty("key", "value");
}};
Parameter allowEmptyCatches allows to suppress violations when tokenlist contains SLIST to check if beginning of block is surrounded bywhitespace and catch block is empty, for example:
try {
k = 5 / i;
} catch (ArithmeticException ex) {}
With this property turned off, this raises violation because the beginning of thecatch block (left curly bracket) is not separated from the end of the catchblock (right curly bracket).
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.
Package: com.puppycrawl.tools.checkstyle.checks.whitespace From 3d07ebe58b25a53f8644801a74d866ecc5e0ca81 Mon Sep 17 00:00:00 2001 From: Abby Edwards