Since Checkstyle 5.3
for
blocks to a specified depth.name | description | type | default value | since |
---|---|---|---|---|
max | Specify maximum allowed nesting depth. | int | 1 |
5.3 |
To configure the check:
<module name="Checker"> <module name="TreeWalker"> <module name="NestedForDepth"/> </module> </module>
Example:
public class Example1 { public void myTest() { for(int i=0; i<10; i++) { for(int j=0; j<i; j++) { } } // violation 3 lines below 'Nested for depth is 2 (max allowed is 1).' for(int i=0; i<10; i++) { for(int j=0; j<i; j++) { for(int k=0; k<j; k++) { } } } // violation 4 lines below 'Nested for depth is 2 (max allowed is 1).' // violation 4 lines below 'Nested for depth is 3 (max allowed is 1).' for(int i=0; i<10; i++) { for(int j=0; j<i; j++) { for(int k=0; k<j; k++) { for(int l=0; l<k; l++) { } } } } } }
To configure the check to allow nesting depth 2:
<module name="Checker"> <module name="TreeWalker"> <module name="NestedForDepth"> <property name="max" value="2"/> </module> </module> </module>
Example:
public class Example2 { public void myTest() { for(int i=0; i<10; i++) { for(int j=0; j<i; j++) { } } for(int i=0; i<10; i++) { for(int j=0; j<i; j++) { for(int k=0; k<j; k++) { } } } // violation 4 lines below 'Nested for depth is 3 (max allowed is 2).' for(int i=0; i<10; i++) { for(int j=0; j<i; j++) { for(int k=0; k<j; k++) { for(int l=0; l<k; l++) { } } } } } }
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.coding