Since Checkstyle 3.1
Finds nested blocks (blocks that are used freely in the code).
Rationale: Nested blocks are often leftovers from the debugging process, they confuse the reader.
For example, this check finds the obsolete braces in
public void guessTheOutput() { int whichIsWhich = 0; { whichIsWhich = 2; } System.out.println("value = " + whichIsWhich); }
and debugging / refactoring leftovers such as
// if (conditionThatIsNotUsedAnyLonger) { System.out.println("unconditional"); }
A case in a switch statement does not implicitly form a block. Thus to be able to introduce local variables that have case scope it is necessary to open a nested block. This is supported, set the allowInSwitchCase property to true and include all statements of the case in the block.
name | description | type | default value | since |
---|---|---|---|---|
allowInSwitchCase | Allow nested blocks if they are the only child of a switch case. | boolean | false |
3.2 |
To configure the check:
<module name="AvoidNestedBlocks"/>
Example:
public void foo() { int myInteger = 0; { // violation myInteger = 2; } System.out.println("myInteger = " + myInteger); switch (a) { case 1: { // violation System.out.println("Case 1"); break; } case 2: System.out.println("Case 2"); // OK break; } }
To configure the check to allow nested blocks in switch case:
<module name="AvoidNestedBlocks"> <property name="allowInSwitchCase" value="true"/> </module>
Example:
public void foo() { int myInteger = 0; { // violation myInteger = 2; } System.out.println("myInteger = " + myInteger); switch (a) { case 1: { // OK System.out.println("Case 1"); break; } case 2: System.out.println("Case 2"); // OK break; } }
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.blocks
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:
switch (a) { case 1: // no violation case 2: // no violation case 3: someMethod(); { } // no violation default: break; }
NOTE: This check processes LITERAL_CASE and LITERAL_DEFAULT separately. Verification empty block is done for single most nearest {@code case} or {@code default}.
name | description | type | default value | since |
---|---|---|---|---|
option | specify the policy on block contents. | BlockOption | statement |
3.0 |
tokens | tokens to check | subset of tokens LITERAL_WHILE , LITERAL_TRY , LITERAL_CATCH , LITERAL_FINALLY , LITERAL_DO , LITERAL_IF , LITERAL_ELSE , LITERAL_FOR , INSTANCE_INIT , STATIC_INIT , LITERAL_SWITCH , LITERAL_SYNCHRONIZED , LITERAL_CASE , LITERAL_DEFAULT , ARRAY_INIT . | LITERAL_WHILE , LITERAL_TRY , LITERAL_FINALLY , LITERAL_DO , LITERAL_IF , LITERAL_ELSE , LITERAL_FOR , INSTANCE_INIT , STATIC_INIT , LITERAL_SWITCH , LITERAL_SYNCHRONIZED . | 3.0 |
To configure the check:
<module name="EmptyBlock"/>
Example:
public class Test { private void emptyLoop() { for (int i = 0; i < 10; i++) { // violation } try { // violation } catch (Exception e) { // ignored } } }
To configure the check for the text
policy and only try
blocks:
<module name="EmptyBlock"> <property name="option" value="text"/> <property name="tokens" value="LITERAL_TRY"/> </module>
Example:
public class Test { private void emptyLoop() { for (int i = 0; i < 10; i++) { // ignored } // violation on next line try { } catch (Exception e) { // ignored } } }
To configure the check for default in switch block:
<module name="EmptyBlock"> <property name="tokens" value="LITERAL_DEFAULT"/> </module>
Example:
public class Test { private void test(int a) { switch (a) { case 1: someMethod(); default: // OK, as there is no block } switch (a) { case 1: someMethod(); default: {} // 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.blocks
Since Checkstyle 6.4
Checks for empty catch blocks. By default check allows empty catch block with any comment inside.
There are two options to make validation more precise: exceptionVariableName and commentFormat. If both options are specified - they are applied by any of them is matching.
name | description | type | default value | since |
---|---|---|---|---|
exceptionVariableName | Specify the RegExp for the name of the variable associated with exception. If check meets variable name matching specified value - empty block is suppressed. | Pattern | "^$" |
6.4 |
commentFormat | Specify the RegExp for the first comment inside empty catch block. If check meets comment inside empty catch block matching specified format - empty block is suppressed. If it is multi-line comment - only its first line is analyzed. | Pattern | ".*" |
6.4 |
To configure the check to suppress empty catch block if exception's variable name is
expected
or ignore
or there's any comment inside:
<module name="EmptyCatchBlock"> <property name="exceptionVariableName" value="expected|ignore"/> </module>
Such empty blocks would be both suppressed:
try { throw new RuntimeException(); } catch (RuntimeException expected) { } try { throw new RuntimeException(); } catch (RuntimeException ignore) { }
To configure the check to suppress empty catch block if single-line comment inside is "//This is expected":
<module name="EmptyCatchBlock"> <property name="commentFormat" value="This is expected"/> </module>
Such empty block would be suppressed:
try { throw new RuntimeException(); } catch (RuntimeException ex) { //This is expected }
To configure the check to suppress empty catch block if single-line comment inside is "//This is expected" or exception's variable name is "myException" (any option is matching):
<module name="EmptyCatchBlock"> <property name="commentFormat" value="This is expected"/> <property name="exceptionVariableName" value="myException"/> </module>
Such empty blocks would be suppressed:
try { throw new RuntimeException(); } catch (RuntimeException e) { //This is expected } ... try { throw new RuntimeException(); } catch (RuntimeException e) { // This is expected } ... try { throw new RuntimeException(); } catch (RuntimeException e) { // This is expected // some another comment } ... try { throw new RuntimeException(); } catch (RuntimeException e) { /* This is expected */ } ... try { throw new RuntimeException(); } catch (RuntimeException e) { /* * * This is expected * some another comment */ } ... try { throw new RuntimeException(); } catch (RuntimeException myException) { }
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.blocks
Since Checkstyle 3.0
Checks for the placement of left curly braces
('{'
) for code blocks.
name | description | type | default value | since |
---|---|---|---|---|
option | Specify the policy on placement of a left curly brace ('{' ). |
LeftCurlyOption | eol |
3.0 |
ignoreEnums | Allow to ignore enums when left curly brace policy is EOL. | boolean | true |
6.9 |
tokens | tokens to check | subset of tokens ANNOTATION_DEF , CLASS_DEF , CTOR_DEF , ENUM_CONSTANT_DEF , ENUM_DEF , INTERFACE_DEF , LAMBDA , LITERAL_CASE , LITERAL_CATCH , LITERAL_DEFAULT , LITERAL_DO , LITERAL_ELSE , LITERAL_FINALLY , LITERAL_FOR , LITERAL_IF , LITERAL_SWITCH , LITERAL_SYNCHRONIZED , LITERAL_TRY , LITERAL_WHILE , METHOD_DEF , OBJBLOCK , STATIC_INIT , RECORD_DEF , COMPACT_CTOR_DEF . | ANNOTATION_DEF , CLASS_DEF , CTOR_DEF , ENUM_CONSTANT_DEF , ENUM_DEF , INTERFACE_DEF , LAMBDA , LITERAL_CASE , LITERAL_CATCH , LITERAL_DEFAULT , LITERAL_DO , LITERAL_ELSE , LITERAL_FINALLY , LITERAL_FOR , LITERAL_IF , LITERAL_SWITCH , LITERAL_SYNCHRONIZED , LITERAL_TRY , LITERAL_WHILE , METHOD_DEF , OBJBLOCK , STATIC_INIT , RECORD_DEF , COMPACT_CTOR_DEF . | 3.0 |
To configure the check:
<module name="LeftCurly"/>
class Test { // Violation - '{' should be on the previous line private interface TestInterface { // Violation - '{' should be on the previous line } private class MyClass { // OK } enum Colors {RED, // OK BLUE, GREEN; } }
To configure the check to apply the nl
policy to
type blocks:
<module name="LeftCurly"> <property name="option" value="nl"/> <property name="tokens" value="CLASS_DEF,INTERFACE_DEF"/> </module>
class Test { // OK private interface TestInterface { // OK } private class MyClass { // Violation - '{' should be on a new line } enum Colors {RED, // OK BLUE, GREEN; } }
An example of how to configure the check to validate enum definitions:
<module name="LeftCurly"> <property name="ignoreEnums" value="false"/> </module>
class Test { // Violation - '{' should be on the previous line private interface TestInterface { // Violation - '{' should be on the previous line } private class MyClass { // OK } enum Colors {RED, // Violation - '{' should have line break after BLUE, GREEN; } }
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.blocks
Since Checkstyle 3.0
Checks for braces around code blocks.
name | description | type | default value | since |
---|---|---|---|---|
allowSingleLineStatement | allow single-line statements without braces. | boolean | false |
6.5 |
allowEmptyLoopBody | allow loops with empty bodies. | boolean | false |
6.12.1 |
tokens | tokens to check | subset of tokens LITERAL_DO , LITERAL_ELSE , LITERAL_FOR , LITERAL_IF , LITERAL_WHILE , LITERAL_CASE , LITERAL_DEFAULT , LAMBDA . | LITERAL_DO , LITERAL_ELSE , LITERAL_FOR , LITERAL_IF , LITERAL_WHILE . | 3.0 |
To configure the check:
<module name="NeedBraces"/>
To configure the check for if
and
else
blocks:
<module name="NeedBraces"> <property name="tokens" value="LITERAL_IF, LITERAL_ELSE"/> </module>
To configure the check to allow single-line statements
(if, while, do-while, for
) without braces:
<module name="NeedBraces"> <property name="allowSingleLineStatement" value="true"/> </module>
Next statements won't be violated by check:
if (obj.isValid()) return true; // OK while (obj.isValid()) return true; // OK do this.notify(); while (o != null); // OK for (int i = 0; ; ) this.notify(); // OK
To configure the check to allow case, default
single-line statements
without braces:
<module name="NeedBraces"> <property name="tokens" value="LITERAL_CASE, LITERAL_DEFAULT"/> <property name="allowSingleLineStatement" value="true"/> </module>
Next statements won't be violated by check:
switch (num) { case 1: counter++; break; // OK case 6: counter += 10; break; // OK default: counter = 100; break; // OK }
To configure the check to allow loops (while, for
) with empty bodies:
<module name="NeedBraces"> <property name="allowEmptyLoopBody" value="true"/> </module>
Next statements won't be violated by check:
while (value.incrementValue() < 5); // OK for(int i = 0; i < 10; value.incrementValue()); // OK
To configure the check to lambdas:
<module name="NeedBraces"> <property name="tokens" value="LAMBDA"/> <property name="allowSingleLineStatement" value="true"/> </module>
Results in following:
allowedFuture.addCallback(result -> assertEquals("Invalid response", EnumSet.of(HttpMethod.GET, HttpMethod.OPTIONS), result), // violation, lambda spans 2 lines ex -> fail(ex.getMessage())); // OK allowedFuture.addCallback(result -> { return assertEquals("Invalid response", EnumSet.of(HttpMethod.GET, HttpMethod.OPTIONS), result); }, // OK ex -> fail(ex.getMessage()));
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.blocks
Since Checkstyle 3.0
Checks the placement of right curly braces ('}'
) for code blocks.
This check supports if-else, try-catch-finally blocks, while-loops, for-loops,
method definitions, class definitions, constructor definitions,
instance, static initialization blocks, annotation definitions and enum definitions.
For right curly brace of expression blocks of arrays, lambdas and class instances
please follow issue
#5945.
For right curly brace of enum constant please follow issue
#7519.
name | description | type | default value | since |
---|---|---|---|---|
option | Specify the policy on placement of a right curly brace ('}' ). |
RightCurlyOption | same |
3.0 |
tokens | tokens to check | subset of tokens LITERAL_TRY , LITERAL_CATCH , LITERAL_FINALLY , LITERAL_IF , LITERAL_ELSE , CLASS_DEF , METHOD_DEF , CTOR_DEF , LITERAL_FOR , LITERAL_WHILE , LITERAL_DO , STATIC_INIT , INSTANCE_INIT , ANNOTATION_DEF , ENUM_DEF , INTERFACE_DEF , RECORD_DEF , COMPACT_CTOR_DEF . | LITERAL_TRY , LITERAL_CATCH , LITERAL_FINALLY , LITERAL_IF , LITERAL_ELSE . | 3.0 |
To configure the check:
<module name="RightCurly"/>
Example:
public class Test { public void test() { if (foo) { bar(); } // violation, right curly must be in the same line as the 'else' keyword else { bar(); } if (foo) { bar(); } else { // OK bar(); } if (foo) { bar(); } int i = 0; // violation // ^^^ statement is not allowed on same line after curly right brace if (foo) { bar(); } // OK int i = 0; try { bar(); } // violation, rightCurly must be in the same line as 'catch' keyword catch (Exception e) { bar(); } try { bar(); } catch (Exception e) { // OK bar(); } } // OK public void testSingleLine() { bar(); } // OK, because singleline is allowed }
To configure the check with policy alone
for else
and
METHOD_DEF
tokens:
<module name="RightCurly"> <property name="option" value="alone"/> <property name="tokens" value="LITERAL_ELSE, METHOD_DEF"/> </module>
Example:
public class Test { public void test() { if (foo) { bar(); } else { bar(); } // violation, right curly must be alone on line if (foo) { bar(); } else { bar(); } // OK try { bar(); } catch (Exception e) { // OK because config is set to token METHOD_DEF and LITERAL_ELSE bar(); } } // OK public void violate() { bar; } // violation, singleline is not allowed here public void ok() { bar(); } // OK }
To configure the check with policy alone_or_singleline
for if
and
METHOD_DEF
tokens:
<module name="RightCurly"> <property name="option" value="alone_or_singleline"/> <property name="tokens" value="LITERAL_IF, METHOD_DEF"/> </module>
Example:
public class Test { public void test() { if (foo) { bar(); } else { // violation, right curly must be alone on line bar(); } if (foo) { bar(); } // OK else { bar(); } try { bar(); } catch (Exception e) { // OK because config did not set token LITERAL_TRY bar(); } } // OK public void violate() { bar(); } // OK , because singleline }
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.blocks