Checkstyle Block Checks
Rules ¶
Avoid nested blocks. [Mandatory] ¶
Nested blocks are often leftovers from the debugging process, they confuse the reader.
public class foo { public void guessTheOutput() { int whichIsWhich = 0; { // violation whichIsWhich = 2; } System.out.println("value = " + whichIsWhich); } }
public class foo { 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"); break; } } }
check AvoidNestedBlocks for the original rule.
Avoid empty block. [Recommended] ¶
Checks for empty blocks.
This check processes 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 separately.
![]()
public class Test { private void emptyLoop() { for (int i = 0; i < 10; i++) { // violation } try { // violation } catch (Exception e) { // ignored } } }
Require that there is some text in the block. For example:
![]()
public class Test { private void emptyLoop() { for (int i = 0; i < 10; i++) { // ignored } // violation on next line try { } catch (Exception e) { // ignored } } }
Check for default in switch block. For example:
private void test(int a) { switch (a) { case 1: someMethod(); default: // OK, as there is no block } switch (a) { case 1: someMethod(); default: {} // violation } }
check EmptyBlock for the original rule.
Check for the placement of left curly braces. [Reference] ¶
Checks for the placement of left curly braces '{' for code blocks.
Example:
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; } }
check LeftCurly for the original rule.
Check for braces around code blocks. [Recommended] ¶
Checks for braces around code blocks.
Example:
if (obj.isValid()) return true; // OK if (true) { // OK return true; } else // OK return false; for (int i = 0; i < 5; i++) { // OK ++count; } do // OK ++count; while (false); for (int j = 0; j < 10; j++); // violation, empty loop body not allowed for(int i = 0; i < 10; value.incrementValue()); // violation, empty loop body not allowed while (counter < 10) // OK ++count; while (value.incrementValue() < 5); // violation, empty loop body not allowed switch (num) { case 1: counter++; break; // OK } while (obj.isValid()) return true; // OK do this.notify(); while (o != null); // OK for (int i = 0; ; ) this.notify(); // OK
check NeedBraces for the original rule.