View Javadoc
1   /*
2    * SPDX-FileCopyrightText: Copyright (c) 2011-2026 Yegor Bugayenko
3    * SPDX-License-Identifier: MIT
4    */
5   package com.qulice.checkstyle;
6   
7   import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
8   import com.puppycrawl.tools.checkstyle.api.DetailAST;
9   import com.puppycrawl.tools.checkstyle.api.TokenTypes;
10  
11  /**
12   * Forbids nested {@code switch} statements.
13   *
14   * <p>A {@code switch} inside another {@code switch} hides flow of control
15   * behind two levels of branching and almost always signals that the enclosing
16   * method is doing too much. Extract the inner statement into its own method
17   * instead. Mirrors Checkstyle's built-in {@code NestedIfDepth},
18   * {@code NestedForDepth} and {@code NestedTryDepth} modules.</p>
19   *
20   * @since 0.24
21   */
22  public final class NestedSwitchCheck extends AbstractCheck {
23  
24      @Override
25      public int[] getDefaultTokens() {
26          return this.getRequiredTokens();
27      }
28  
29      @Override
30      public int[] getAcceptableTokens() {
31          return this.getRequiredTokens();
32      }
33  
34      @Override
35      public int[] getRequiredTokens() {
36          return new int[] {TokenTypes.LITERAL_SWITCH};
37      }
38  
39      @Override
40      public void visitToken(final DetailAST ast) {
41          DetailAST parent = ast.getParent();
42          while (parent != null) {
43              if (parent.getType() == TokenTypes.LITERAL_SWITCH) {
44                  this.log(ast.getLineNo(), "Nested switch statements are not allowed");
45                  break;
46              }
47              parent = parent.getParent();
48          }
49      }
50  }