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      /**
25       * Default constructor.
26       */
27      public NestedSwitchCheck() {
28          // nothing to initialize
29      }
30  
31      @Override
32      public int[] getDefaultTokens() {
33          return this.getRequiredTokens();
34      }
35  
36      @Override
37      public int[] getAcceptableTokens() {
38          return this.getRequiredTokens();
39      }
40  
41      @Override
42      public int[] getRequiredTokens() {
43          return new int[] {TokenTypes.LITERAL_SWITCH};
44      }
45  
46      @Override
47      public void visitToken(final DetailAST ast) {
48          DetailAST parent = ast.getParent();
49          while (parent != null) {
50              if (parent.getType() == TokenTypes.LITERAL_SWITCH) {
51                  this.log(ast.getLineNo(), "Nested switch statements are not allowed");
52                  break;
53              }
54              parent = parent.getParent();
55          }
56      }
57  }