NestedIfDepth

Since Checkstyle 3.2

Description

Restricts nested if-else blocks to a specified depth.

Properties

name description type default value since
max Specify maximum allowed nesting depth. int 1 3.2

Examples

To configure the check:

<module name="Checker">
  <module name="TreeWalker">
    <module name="NestedIfDepth"/>
  </module>
</module>
        

Valid code example:

if (true) {
    if (true) {} // OK
    else {}
}
        

Invalid code example:

if (true) {
    if (true) {
        if (true) { // violation, nested if-else depth is 2 (max allowed is 1)
        }
    }
}
        

To configure the check to allow nesting depth 3:

<module name="Checker">
  <module name="TreeWalker">
    <module name="NestedIfDepth">
      <property name="max" value="3"/>
    </module>
  </module>
</module>
        

Valid code example:

if (true) {
   if (true) {
      if (true) {
         if (true) {} // OK
         else {}
      }
   }
}
        

Invalid code example:

if (true) {
   if (true) {
      if (true) {
         if (true) {
            if (true) { // violation, nested if-else depth is 4 (max allowed is 3)
               if (true) {} // violation, nested if-else depth is 5 (max allowed is 3)
               else {}
            }
         }
      }
   }
}
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker