Since Checkstyle 3.1
Checks the style of array type definitions. Some like Java style:
public static void main(String[] args)
and some like
C style: public static void main(String args[])
.
By default the Check enforces Java style.
This check strictly enforces only Java style for method return types
regardless of the value for 'javaStyle'. For example, byte[] getData()
.
This is because C doesn't compile methods with array declarations on the name.
name | description | type | default value | since |
---|---|---|---|---|
javaStyle | Control whether to enforce Java style (true) or C style (false). | boolean | true |
3.1 |
To configure the check to enforce Java style:
<module name="ArrayTypeStyle"/>
Example:
public class MyClass { int[] nums; // OK String strings[]; // violation char[] toCharArray() { // OK return null; } byte getData()[] { // violation return null; } }
To configure the check to enforce C style:
<module name="ArrayTypeStyle"> <property name="javaStyle" value="false"/> </module>
Example:
public class MyClass { int[] nums; // violation String strings[]; // OK char[] toCharArray() { // OK return null; } byte getData()[] { // violation return null; } }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks
Since Checkstyle 5.8
Restricts using Unicode escapes (such as \u221e). It is possible to allow using escapes for non-printable, control characters. Also, this check can be configured to allow using escapes if trail comment is present. By the option it is possible to allow using escapes if literal contains only them.
name | description | type | default value | since |
---|---|---|---|---|
allowEscapesForControlCharacters | Allow use escapes for non-printable, control characters. | boolean | false |
5.8 |
allowByTailComment | Allow use escapes if trail comment is present. | boolean | false |
5.8 |
allowIfAllCharactersEscaped | Allow if all characters in literal are escaped. | boolean | false |
5.8 |
allowNonPrintableEscapes | Allow use escapes for non-printable, whitespace characters. | boolean | false |
5.8 |
To configure the check:
<module name="AvoidEscapedUnicodeCharacters"/>
Examples of using Unicode:
String unitAbbrev = "μs"; // Best: perfectly clear even without a comment. String unitAbbrev = "\u03bcs"; // Poor: the reader has no idea what this is.
An example of non-printable, control characters.
return '\ufeff' + content; // byte order mark
An example of how to configure the check to allow using escapes for non-printable, control characters:
<module name="AvoidEscapedUnicodeCharacters"> <property name="allowEscapesForControlCharacters" value="true"/> </module>
Example of using escapes with trail comment:
String unitAbbrev = "\u03bcs"; // Greek letter mu, "s" String textBlockUnitAbbrev = """ \u03bcs"""; // Greek letter mu, "s"
An example of how to configure the check to allow using escapes if trail comment is present:
<module name="AvoidEscapedUnicodeCharacters"> <property name="allowByTailComment" value="true"/> </module>
Example of using escapes if literal contains only them:
String unitAbbrev = "\u03bc\u03bc\u03bc";
An example of how to configure the check to allow escapes if literal contains only them:
<module name="AvoidEscapedUnicodeCharacters"> <property name="allowIfAllCharactersEscaped" value="true"/> </module>
An example of how to configure the check to allow using escapes for non-printable, whitespace characters:
<module name="AvoidEscapedUnicodeCharacters"> <property name="allowNonPrintableEscapes" value="true"/> </module>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks
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.
1 /* 2 * it is Ok 3 */ 4 boolean bool = true; 5 6 /* violation 7 * (block comment should have the same indentation level as line 9) 8 */ 9 double d = 3.14;
Example #2: Comment is placed at the end of the block and has previous statement.
1 public void foo1() { 2 foo2(); 3 // it is OK 4 } 5 6 public void foo2() { 7 foo3(); 8 // violation (comment should have the same indentation level as line 7) 9 }
Example #3: Comment is used as a single line border to separate groups of methods.
1 /////////////////////////////// it is OK 2 3 public void foo7() { 4 int a = 0; 5 } 6 7 ///////////////////////////// violation (should have the same indentation level as line 9) 8 9 public void foo8() {}
Example #4: Comment has distributed previous statement.
1 public void foo11() { 2 CheckUtil 3 .getFirstNode(new DetailAST()) 4 .getFirstChild() 5 .getNextSibling(); 6 // it is OK 7 } 8 9 public void foo12() { 10 CheckUtil 11 .getFirstNode(new DetailAST()) 12 .getFirstChild() 13 .getNextSibling(); 14 // violation (should have the same indentation level as line 10) 15 }
Example #5: Single line block comment is placed within an empty code block. Note, if comment is placed at the end of the empty code block, we have Checkstyle's limitations to clearly detect user intention of explanation target - above or below. The only case we can assume as a violation is when a single line comment within the empty code block has indentation level that is lower than the indentation level of the closing right curly brace.
1 public void foo46() { 2 // comment 3 // block 4 // it is OK (we cannot clearly detect user intention of explanation target) 5 } 6 7 public void foo46() { 8 // comment 9 // block 10 // violation (comment should have the same indentation level as line 11) 11 }
Example #6: 'fallthrough' comments and similar.
0 switch(a) { 1 case "1": 2 int k = 7; 3 // it is OK 4 case "2": 5 int k = 7; 6 // it is OK 7 case "3": 8 if (true) {} 9 // violation (should have the same indentation level as line 8 or 10) 10 case "4": 11 case "5": { 12 int a; 13 } 14 // fall through (it is OK) 15 case "12": { 16 int a; 17 } 18 default: 19 // it is OK 20 }
Example #7: Comment is placed within a distributed statement.
1 String breaks = "J" 2 // violation (comment should have the same indentation level as line 3) 3 + "A" 4 // it is OK 5 + "V" 6 + "A" 7 // it is OK 8 ;
Example #8: Comment is placed within an empty case block. Note, if comment is placed at the end of the empty case block, we have Checkstyle's limitations to clearly detect user intention of explanation target - above or below. The only case we can assume as a violation is when a single line comment within the empty case block has indentation level that is lower than the indentation level of the next case token.
1 case 4: 2 // it is OK 3 case 5: 4 // violation (should have the same indentation level as line 3 or 5) 5 case 6:
Example #9: Single line block comment has previous and next statement.
1 String s1 = "Clean code!"; 2 s.toString().toString().toString(); 3 // single line 4 // block 5 // comment (it is OK) 6 int a = 5; 7 8 String s2 = "Code complete!"; 9 s.toString().toString().toString(); 10 // violation (should have the same indentation level as line 11) 11 // violation (should have the same indentation level as line 12) 12 // violation (should have the same indentation level as line 13) 13 int b = 18;
Example #10: Comment within the block tries to describe the next code block.
1 public void foo42() { 2 int a = 5; 3 if (a == 5) { 4 int b; 5 // it is OK 6 } else if (a ==6) { ... } 7 } 8 9 public void foo43() { 10 try { 11 int a; 12 // Why do we catch exception here? - violation (not the same indentation as line 11) 13 } catch (Exception e) { ... } 14 }
name | description | type | default value | since |
---|---|---|---|---|
tokens | tokens to check | subset of tokens SINGLE_LINE_COMMENT , BLOCK_COMMENT_BEGIN . | SINGLE_LINE_COMMENT , BLOCK_COMMENT_BEGIN . | 6.10 |
To configure the Check:
<module name="CommentsIndentation"/>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.indentation
Since Checkstyle 3.2
Checks for restricted tokens beneath other tokens.
WARNING: This is a very powerful and flexible check, but, at the same time, it is low-level and very implementation-dependent because its results depend on the grammar we use to build abstract syntax trees. Thus we recommend using other checks when they provide the desired functionality. Essentially, this check just works on the level of an abstract syntax tree and knows nothing about language structures.
name | description | type | default value | since |
---|---|---|---|---|
limitedTokens | Specify set of tokens with limited occurrences as descendants. | subset of tokens TokenTypes | {} |
3.2 |
minimumDepth | Specify the minimum depth for descendant counts. | int | 0 |
3.2 |
maximumDepth | Specify the maximum depth for descendant counts. | int | 2147483647 |
3.2 |
minimumNumber | Specify a minimum count for descendants. | int | 0 |
3.2 |
maximumNumber | Specify a maximum count for descendants. | int | 2147483647 |
3.2 |
sumTokenCounts | Control whether the number of tokens found should be calculated from the sum of the individual token counts. | boolean | false |
5.0 |
minimumMessage | Define the violation message when the minimum count is not reached. | String | null |
3.2 |
maximumMessage | Define the violation message when the maximum count is exceeded. | String | null |
3.2 |
tokens | tokens to check | set of any supported tokens | empty |
3.2 |
To configure the check to produce a violation on a switch statement with no default case:
<module name="DescendantToken"> <property name="tokens" value="LITERAL_SWITCH"/> <property name="maximumDepth" value="2"/> <property name="limitedTokens" value="LITERAL_DEFAULT"/> <property name="minimumNumber" value="1"/> </module>
To configure the check to produce a violation on a
condition in for
which performs no check:
<module name="DescendantToken"> <property name="tokens" value="FOR_CONDITION"/> <property name="limitedTokens" value="EXPR"/> <property name="minimumNumber" value="1"/> </module>
To configure the check to produce a violation on
comparing this
with null
(i.e. this ==
null
and this != null
):
<module name="DescendantToken"> <property name="tokens" value="EQUAL,NOT_EQUAL"/> <property name="limitedTokens" value="LITERAL_THIS,LITERAL_NULL"/> <property name="maximumNumber" value="1"/> <property name="maximumDepth" value="1"/> <property name="sumTokenCounts" value="true"/> </module>
To configure the check to produce a violation on a String
literal equality check:
<module name="DescendantToken"> <property name="tokens" value="EQUAL,NOT_EQUAL"/> <property name="limitedTokens" value="STRING_LITERAL"/> <property name="maximumNumber" value="0"/> <property name="maximumDepth" value="1"/> </module>
To configure the check to produce a violation on an assert statement that may have side effects (formatted for browser display):
<module name="DescendantToken"> <property name="tokens" value="LITERAL_ASSERT"/> <property name="limitedTokens" value="ASSIGN,DEC,INC,POST_DEC, POST_INC,PLUS_ASSIGN,MINUS_ASSIGN,STAR_ASSIGN,DIV_ASSIGN,MOD_ASSIGN, BSR_ASSIGN,SR_ASSIGN,SL_ASSIGN,BAND_ASSIGN,BXOR_ASSIGN,BOR_ASSIGN, METHOD_CALL"/> <property name="maximumNumber" value="0"/> </module>
To configure the check to produce a violation on an initializer in
for
performs no setup (where a while
statement could be used instead):
<module name="DescendantToken"> <property name="tokens" value="FOR_INIT"/> <property name="limitedTokens" value="EXPR"/> <property name="minimumNumber" value="1"/> </module>
To configure the check to produce a violation on a switch that is nested in another switch:
<module name="DescendantToken"> <property name="tokens" value="LITERAL_SWITCH"/> <property name="limitedTokens" value="LITERAL_SWITCH"/> <property name="maximumNumber" value="0"/> <property name="minimumDepth" value="1"/> </module>
To configure the check to produce a violation on a return statement from within a catch or finally block:
<module name="DescendantToken"> <property name="tokens" value="LITERAL_FINALLY,LITERAL_CATCH"/> <property name="limitedTokens" value="LITERAL_RETURN"/> <property name="maximumNumber" value="0"/> </module>
To configure the check to produce a violation on a try statement within a catch or finally block:
<module name="DescendantToken"> <property name="tokens" value="LITERAL_CATCH,LITERAL_FINALLY"/> <property name="limitedTokens" value="LITERAL_TRY"/> <property name="maximumNumber" value="0"/> </module>
To configure the check to produce a violation on a switch with too many cases:
<module name="DescendantToken"> <property name="tokens" value="LITERAL_SWITCH"/> <property name="limitedTokens" value="LITERAL_CASE"/> <property name="maximumDepth" value="2"/> <property name="maximumNumber" value="10"/> </module>
To configure the check to produce a violation on a method with too many local variables:
<module name="DescendantToken"> <property name="tokens" value="METHOD_DEF"/> <property name="limitedTokens" value="VARIABLE_DEF"/> <property name="maximumDepth" value="2"/> <property name="maximumNumber" value="10"/> </module>
To configure the check to produce a violation on a method with too many returns:
<module name="DescendantToken"> <property name="tokens" value="METHOD_DEF"/> <property name="limitedTokens" value="LITERAL_RETURN"/> <property name="maximumNumber" value="3"/> </module>
To configure the check to produce a violation on an interface with too many fields:
<module name="DescendantToken"> <property name="tokens" value="INTERFACE_DEF"/> <property name="limitedTokens" value="VARIABLE_DEF"/> <property name="maximumDepth" value="2"/> <property name="maximumNumber" value="0"/> </module>
To configure the check to produce a violation on a method which throws too many exceptions:
<module name="DescendantToken"> <property name="tokens" value="LITERAL_THROWS"/> <property name="limitedTokens" value="IDENT"/> <property name="maximumNumber" value="1"/> </module>
To configure the check to produce a violation on a method with too many expressions:
<module name="DescendantToken"> <property name="tokens" value="METHOD_DEF"/> <property name="limitedTokens" value="EXPR"/> <property name="maximumNumber" value="200"/> </module>
To configure the check to produce a violation on an empty statement:
<module name="DescendantToken"> <property name="tokens" value="EMPTY_STAT"/> <property name="limitedTokens" value="EMPTY_STAT"/> <property name="maximumNumber" value="0"/> <property name="maximumDepth" value="0"/> <property name="maximumMessage" value="Empty statement is not allowed."/> </module>
To configure the check to produce a violation on a class with too many fields:
<module name="DescendantToken"> <property name="tokens" value="CLASS_DEF"/> <property name="limitedTokens" value="VARIABLE_DEF"/> <property name="maximumDepth" value="2"/> <property name="maximumNumber" value="10"/> </module>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks
Since Checkstyle 3.0
Checks that parameters for methods, constructors, catch and for-each blocks are final. Interface, abstract, and native methods are not checked: the final keyword does not make sense for interface, abstract, and native method parameters as there is no code that could modify the parameter.
Rationale: Changing the value of parameters during the execution of the method's algorithm can be confusing and should be avoided. A great way to let the Java compiler prevent this coding style is to declare parameters final.
name | description | type | default value | since |
---|---|---|---|---|
ignorePrimitiveTypes | Ignore primitive types as parameters. | boolean | false |
6.2 |
tokens | tokens to check | subset of tokens METHOD_DEF , CTOR_DEF , LITERAL_CATCH , FOR_EACH_CLAUSE . | METHOD_DEF , CTOR_DEF . | 3.0 |
To configure the check to enforce final parameters for methods and constructors:
<module name="FinalParameters"/>
To configure the check to enforce final parameters only for constructors:
<module name="FinalParameters"> <property name="tokens" value="CTOR_DEF"/> </module>
To configure the check to allow ignoring primitive datatypes as parameters:
<module name="FinalParameters"> <property name="ignorePrimitiveTypes" value="true"/> </module>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks
Since Checkstyle 3.1
Checks correct indentation of Java code.
The idea behind this is that while pretty printers are sometimes convenient for bulk reformats of legacy code, they often either aren't configurable enough or just can't anticipate how format should be done. Sometimes this is personal preference, other times it is practical experience. In any case, this check should just ensure that a minimal set of indentation rules is followed.
Basic offset indentation is used for indentation inside code blocks. For any lines that span more than 1, line wrapping indentation is used for those lines after the first. Brace adjustment, case, and throws indentations are all used only if those specific identifiers start the line. If, for example, a brace is used in the middle of the line, its indentation will not take effect. All indentations have an accumulative/recursive effect when they are triggered. If during a line wrapping, another code block is found and it doesn't end on that same line, then the subsequent lines afterwards, in that new code block, are increased on top of the line wrap and any indentations above it.
Example:
if ((condition1 && condition2) || (condition3 && condition4) // line wrap with bigger indentation ||!(condition5 && condition6)) { // line wrap with bigger indentation field.doSomething() // basic offset .doSomething() // line wrap .doSomething( c -> { // line wrap return c.doSome(); // basic offset }); }
name | description | type | default value | since |
---|---|---|---|---|
basicOffset | Specify how far new indentation level should be indented when on the next line. | int | 4 |
3.1 |
braceAdjustment | Specify how far a braces should be indented when on the next line. | int | 0 |
3.1 |
caseIndent | Specify how far a case label should be indented when on next line. | int | 4 |
3.1 |
throwsIndent | Specify how far a throws clause should be indented when on next line. | int | 4 |
5.7 |
arrayInitIndent | Specify how far an array initialisation should be indented when on next line. | int | 4 |
5.8 |
lineWrappingIndentation | Specify how far continuation line should be indented when line-wrapping is present. | int | 4 |
5.9 |
forceStrictCondition | Force strict indent level in line wrapping case. If value is true, line wrap indent have to be same as lineWrappingIndentation parameter. If value is false, line wrap indent could be bigger on any value user would like. | boolean | false |
6.3 |
To configure the default check:
<module name="Indentation"/>
Example of Compliant code for default configuration (in comment name of property that controls indentations):
class Test { String field; // basicOffset int[] arr = { // basicOffset 5, // arrayInitIndent 6 }; // arrayInitIndent void bar() throws Exception // basicOffset { // braceAdjustment foo(); // basicOffset } // braceAdjustment void foo() { // basicOffset if ((cond1 && cond2) // basicOffset || (cond3 && cond4) // lineWrappingIndentation, forceStrictCondition ||!(cond5 && cond6)) { // lineWrappingIndentation, forceStrictCondition field.doSomething() // basicOffset .doSomething() // lineWrappingIndentation and forceStrictCondition .doSomething( c -> { // lineWrappingIndentation and forceStrictCondition return c.doSome(); // basicOffset }); } } void fooCase() // basicOffset throws Exception { // throwsIndent switch (field) { // basicOffset case "value" : bar(); // caseIndent } } }
To configure the check to enforce the indentation style recommended by Oracle:
<module name="Indentation"> <property name="caseIndent" value="0"/> </module>
Example of Compliant code for default configuration (in comment name of property that controls indentation):
void fooCase() { // basicOffset switch (field) { // basicOffset case "value" : bar(); // caseIndent } }
To configure the Check to enforce strict condition in line-wrapping validation.
<module name="Indentation"> <property name="forceStrictCondition" value="true"/> </module>
Such config doesn't allow next cases even code is aligned further to the right for better reading:
void foo(String aFooString, int aFooInt) { // indent:8 ; expected: 4; violation, because 8 != 4 if (cond1 || cond2) { field.doSomething() .doSomething(); } if ((cond1 && cond2) || (cond3 && cond4) // violation ||!(cond5 && cond6)) { // violation field.doSomething() .doSomething() // violation .doSomething( c -> { // violation return c.doSome(); }); } }
But if forceStrictCondition = false, this code is valid:
void foo(String aFooString, int aFooInt) { // indent:8 ; expected: > 4; ok, because 8 > 4 if (cond1 || cond2) { field.doSomething() .doSomething(); } if ((cond1 && cond2) || (cond3 && cond4) ||!(cond5 && cond6)) { field.doSomething() .doSomething() .doSomething( c -> { return c.doSome(); }); } }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.indentation
Since Checkstyle 3.1
Checks whether files end with a line separator.
Rationale: Any source files and text files in general should end with a line separator to let other easily add new content at the end of file and "diff" command does not show previous lines as changed.
Example (line 36 should not be in diff):
@@ -32,4 +32,5 @@ ForbidWildcardAsReturnTypeCheck.returnTypeClassNamesIgnoreRegex PublicReferenceToPrivateTypeCheck.name = Public Reference To Private Type StaticMethodCandidateCheck.name = Static Method Candidate -StaticMethodCandidateCheck.desc = Checks whether private methods should be declared as static. \ No newline at end of file +StaticMethodCandidateCheck.desc = Checks whether private methods should be declared as static. +StaticMethodCandidateCheck.skippedMethods = Method names to skip during the check.
It can also trick the VCS to report the wrong owner for such lines. An engineer who has added nothing but a newline character becomes the last known author for the entire line. As a result, a mate can ask him a question to which he will not give the correct answer.
Old Rationale: CVS source control management systems will even print a warning when it encounters a file that doesn't end with a line separator.
Attention: property fileExtensions works with files that are passed by similar property for at Checker. Please make sure required file extensions are mentioned at Checker's fileExtensions property.
This will check against the platform-specific default line separator.
It is also possible to enforce the use of a specific line-separator
across platforms, with the lineSeparator
property.
name | description | type | default value | since |
---|---|---|---|---|
lineSeparator | Specify the type of line separator. | LineSeparatorOption | lf_cr_crlf |
3.1 |
fileExtensions | Specify the file type extension of the files to check. | String[] | all files |
3.1 |
To configure the check:
<module name="NewlineAtEndOfFile"/>
Example:
// File ending with a new line public class Test {⤶ ⤶ }⤶ // ok Note: The comment // ok is a virtual, not actually present in the file // File ending without a new line public class Test1 {⤶ ⤶ } // violation, the file does not end with a new line
To configure the check to always use Unix-style line separators:
<module name="NewlineAtEndOfFile"> <property name="lineSeparator" value="lf"/> </module>
Example:
// File ending with a new line public class Test {⤶ ⤶ }⤶ // ok Note: The comment // ok is a virtual, not actually present in the file // File ending without a new line public class Test1 {⤶ ⤶ }␍⤶ // violation, expected line ending for file is LF(\n), but CRLF(\r\n) is detected
To configure the check to work only on Java, XML and Python files:
<module name="NewlineAtEndOfFile"> <property name="fileExtensions" value="java, xml, py"/> </module>
Example:
// Any java file public class Test {⤶ } // violation, file should end with a new line. // Any py file print("Hello World") // violation, file should end with a new line. // Any txt file This is a sample text file. // ok, this file is not specified in the config.
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks
Since Checkstyle 8.33
Checks whether file contains code. Files which are considered to have no code:
To configure the check:
<module name="NoCodeInFile"/>
Example:
Content of the files:
// single line comment // violation
/* // violation block comment */
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks
Since Checkstyle 8.22
Detects if keys in properties files are in correct order.
Rationale: Sorted properties make it easy for people to find required properties by name
in 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 lines
does not matter at all, but this can be improved.
E.g.: checkstyle/src/main/resources/com/puppycrawl/tools/checkstyle/messages.properties
You may suppress warnings of this check for files that have an logical structure like
build 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.
name | description | type | default value | since |
---|---|---|---|---|
fileExtensions | Specify file type extension of the files to check. | String[] | .properties |
8.22 |
To configure the check:
<module name="OrderedProperties"/>
Example properties file:
A =65 a =97 key =107 than nothing key.sub =k is 107 and dot is 46 key.png =value - violation
We check order of key's only. Here we would like to use an Locale independent order mechanism, an binary order. The order is case insensitive and ascending.
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks
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 named
Foo.java
.
To configure the check:
<module name="OuterTypeFilename"/>
Example of class Test in a file named Test.java
public class Test { // OK }
Example of class Foo in a file named Test.java
class Foo { // violation }
Example of interface Foo in a file named Test.java
interface Foo { // violation }
Example of enum Foo in a file named Test.java
enum Foo { // violation }
Example of record Foo in a file named Test.java
record Foo { // violation }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks
Since Checkstyle 3.0
Checks for TODO:
comments. Actually
it is a generic
regular
expression matcher on Java comments. To check for other
patterns in Java comments, set the format
property.
name | description | type | default value | since |
---|---|---|---|---|
format | Specify pattern to match comments against. | Pattern | "TODO:" |
3.0 |
Using TODO:
comments is a great way
to keep track of tasks that need to be done. Having them
reported by Checkstyle makes it very hard to forget about
them.
To configure the check:
<module name="TodoComment"/>
Example:
i++; // TODO: do differently in future // violation i++; // todo: do differently in future // OK
To configure the check for comments that contain TODO
and FIXME
:
<module name="TodoComment"> <property name="format" value="(TODO)|(FIXME)"/> </module>
Example:
i++; // TODO: do differently in future // violation i++; // todo: do differently in future // OK i=i/x; // FIXME: handle x = 0 case // violation i=i/x; // FIX : handle x = 0 case // OK
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks
Since Checkstyle 3.4
The check to ensure that requires that comments be the only thing on
a line. For the case of //
comments that means that the only thing
that should precede it is whitespace. It doesn't check comments if
they do not end a line; for example, it accepts the following:
Thread.sleep( 10 /*some comment here*/ );
Format
property is intended to deal with the } // while
example.
Rationale: Steve McConnell in Code Complete suggests that endline comments are a bad practice. An end line comment would be one that is on the same line as actual code. For example:
a = b + c; // Some insightful comment d = e / f; // Another comment for this line
Quoting Code Complete for the justification:
McConnell's comments on being hard to maintain when the size of the line changes are even more important in the age of automated refactorings.
name | description | type | default value | since |
---|---|---|---|---|
format | Specify pattern for strings allowed before the comment. | Pattern | "^[\s});]*$" |
3.4 |
legalComment | Define pattern for text allowed in trailing comments. (This pattern will not be applied to multiline comments and the text of the comment will be trimmed before matching.) | Pattern | null |
4.2 |
To configure the check:
<module name="TrailingComment"/>
To configure the check so it enforces only comment on a line:
<module name="TrailingComment"> <property name="format" value="^\\s*$"/> </module>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks
Since Checkstyle 3.0
Ensures the correct translation of code by checking property files for
consistency regarding their keys. Two property files
describing one and the same context are consistent if they
contain the same keys. TranslationCheck also can check an existence of required
translations which must exist in project, if requiredTranslations
option is used.
Consider the following properties file in the same directory:
#messages.properties hello=Hello cancel=Cancel #messages_de.properties hell=Hallo ok=OK
The Translation check will find the typo in the German hello
key, the missing ok
key in the default resource file and the
missing cancel
key in the German resource file:
messages_de.properties: Key 'hello' missing. messages_de.properties: Key 'cancel' missing. messages.properties: Key 'hell' missing. messages.properties: Key 'ok' missing.
Language code for the property requiredTranslations
is composed of
the lowercase, two-letter codes as defined by
ISO 639-1.
Default value is empty String Set which means that only the existence
of default translation is checked. Note, if you specify language codes (or just
one language code) of required translations the check will also check for
existence of default translation files in project.
Attention: the check will perform the validation of ISO codes if the option is used. So, if you specify, for example, "mm" for language code, TranslationCheck will rise violation that the language code is incorrect.
Attention: this Check could produce false-positives if it is used with Checker that use cache (property "cacheFile") This is known design problem, will be addressed at issue.
name | description | type | default value | since |
---|---|---|---|---|
fileExtensions |
Specify file type extension to identify translation files. Setting
this property is typically only required if your
translation files are preprocessed and the original files
do not have the extension .properties
|
String[] | .properties |
3.0 |
baseName | Specify Base name of resource bundles which contain message resources. It helps the check to distinguish config and localization resources. | Pattern | "^messages.*$" |
6.17 |
requiredTranslations | Specify language codes of required translations which must exist in project. | String[] | {} |
6.11 |
To configure the check to check only files which have '.properties' and '.translations' extensions:
<module name="Translation"> <property name="fileExtensions" value="properties, translations"/> </module>
Note, that files with the same path and base name but which have different extensions will be considered as files that belong to different resource bundles.
An example of how to configure the check to validate only bundles which base names start with "ButtonLabels":
<module name="Translation"> <property name="baseName" value="^ButtonLabels.*$"/> </module>
To configure the check to check existence of Japanese and French translations:
<module name="Translation"> <property name="requiredTranslations" value="ja, fr"/> </module>
The following example shows how the check works if there is a message bundle which element name contains language code, county code, platform name. Consider that we have the below configuration:
<module name="Translation"> <property name="requiredTranslations" value="es, fr, de"/> </module>
As we can see from the configuration, the TranslationCheck was configured to check an existence of 'es', 'fr' and 'de' translations. Lets assume that we have the resource bundle:
messages_home.properties messages_home_es_US.properties messages_home_fr_CA_UNIX.properties
Than the check will rise the following violation: "0: Properties file 'messages_home_de.properties' is missing."
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks
Since Checkstyle 3.2
Detects uncommented main
methods.
Rationale: A main
method is often used for debugging
purposes. When debugging is finished, developers often forget
to remove the method, which changes the API and increases the
size of the resulting class or JAR file. With the exception of
the real program entry points, all main
methods should be
removed or commented out of the sources.
name | description | type | default value | since |
---|---|---|---|---|
excludedClasses | Specify pattern for qualified names of classes which are allowed
to have a main method. |
Pattern | "^$" |
3.2 |
To configure the check:
<module name="UncommentedMain"/>
Example:
public class Game { public static void main(String... args){} // violation } public class Main { public static void main(String[] args){} // violation } public class Launch { //public static void main(String[] args){} // OK } public class Start { public void main(){} // OK } public record MyRecord1 { public void main(){} // violation } public record MyRecord2 { //public void main(){} // OK }
To configure the check to allow the main
method for all classes
with "Main" name:
<module name="UncommentedMain"> <property name="excludedClasses" value="\.Main$"/> </module>
Example:
public class Game { public static void main(String... args){} // violation } public class Main { public static void main(String[] args){} // OK } public class Launch { //public static void main(String[] args){} // OK } public class Start { public void main(){} // OK } public record MyRecord1 { public void main(){} // OK }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks
Since Checkstyle 5.7
Detects duplicated keys in properties files.
Rationale: Multiple property keys usually appear after merge or rebase of several branches. While there are no problems in runtime, there can be a confusion due to having different values for the duplicated properties.
name | description | type | default value | since |
---|---|---|---|---|
fileExtensions | Specify file type extension of the files to check. | String[] | .properties |
5.7 |
To configure the check:
<module name="UniqueProperties"> <property name="fileExtensions" value="properties" /> </module>
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks
Since Checkstyle 3.0
Checks that long constants are defined with an upper ell. That
is 'L'
and not 'l'
. This is in accordance with the Java
Language Specification,
Section 3.10.1.
Rationale: The lower-case ell 'l'
looks a lot like 1
.
To configure the check:
<module name="UpperEll"/>
class Test { long var1 = 508987; // OK long var2 = 508987l; // violation long var3 = 508987L; // OK }
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks