View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2025 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.checks.coding;
21  
22  import java.util.ArrayList;
23  import java.util.List;
24  import java.util.Optional;
25  
26  import com.puppycrawl.tools.checkstyle.StatelessCheck;
27  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
28  import com.puppycrawl.tools.checkstyle.api.DetailAST;
29  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
30  
31  /**
32   * <div>
33   * Checks that all constructors are grouped together.
34   * If there is any non-constructor code separating constructors,
35   * this check identifies and logs a violation for those ungrouped constructors.
36   * The violation message will specify the line number of the last grouped constructor.
37   * Comments between constructors are allowed.
38   * </div>
39   *
40   * <p>
41   * Rationale: Grouping constructors together in a class improves code readability
42   * and maintainability. It allows developers to easily understand
43   * the different ways an object can be instantiated
44   * and the tasks performed by each constructor.
45   * </p>
46   *
47   * <p>
48   * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
49   * </p>
50   *
51   * <p>
52   * Violation Message Keys:
53   * </p>
54   * <ul>
55   * <li>
56   * {@code constructors.declaration.grouping}
57   * </li>
58   * </ul>
59   *
60   * @since 10.17.0
61   */
62  
63  @StatelessCheck
64  public class ConstructorsDeclarationGroupingCheck extends AbstractCheck {
65  
66      /**
67       * A key is pointing to the warning message text in "messages.properties"
68       * file.
69       */
70      public static final String MSG_KEY = "constructors.declaration.grouping";
71  
72      @Override
73      public int[] getDefaultTokens() {
74          return getRequiredTokens();
75      }
76  
77      @Override
78      public int[] getAcceptableTokens() {
79          return getRequiredTokens();
80      }
81  
82      @Override
83      public int[] getRequiredTokens() {
84          return new int[] {
85              TokenTypes.CLASS_DEF,
86              TokenTypes.ENUM_DEF,
87              TokenTypes.RECORD_DEF,
88          };
89      }
90  
91      @Override
92      public void visitToken(DetailAST ast) {
93          // list of all child ASTs
94          final List<DetailAST> children = getChildList(ast);
95  
96          // find first constructor
97          final DetailAST firstConstructor = children.stream()
98                  .filter(ConstructorsDeclarationGroupingCheck::isConstructor)
99                  .findFirst()
100                 .orElse(null);
101 
102         if (firstConstructor != null) {
103 
104             // get all children AST after the first constructor
105             final List<DetailAST> childrenAfterFirstConstructor =
106                     children.subList(children.indexOf(firstConstructor), children.size());
107 
108             // find the first index of non-constructor AST after the first constructor, if present
109             final Optional<Integer> indexOfFirstNonConstructor = childrenAfterFirstConstructor
110                     .stream()
111                     .filter(currAst -> !isConstructor(currAst))
112                     .findFirst()
113                     .map(children::indexOf);
114 
115             // list of all children after first non-constructor AST
116             final List<DetailAST> childrenAfterFirstNonConstructor = indexOfFirstNonConstructor
117                     .map(index -> children.subList(index, children.size()))
118                     .orElseGet(ArrayList::new);
119 
120             // create a list of all constructors that are not grouped to log
121             final List<DetailAST> constructorsToLog = childrenAfterFirstNonConstructor.stream()
122                     .filter(ConstructorsDeclarationGroupingCheck::isConstructor)
123                     .toList();
124 
125             // find the last grouped constructor
126             final DetailAST lastGroupedConstructor = childrenAfterFirstConstructor.stream()
127                     .takeWhile(ConstructorsDeclarationGroupingCheck::isConstructor)
128                     .reduce((first, second) -> second)
129                     .orElse(firstConstructor);
130 
131             // log all constructors that are not grouped
132             constructorsToLog
133                     .forEach(ctor -> log(ctor, MSG_KEY, lastGroupedConstructor.getLineNo()));
134         }
135     }
136 
137     /**
138      * Get a list of all children of the given AST.
139      *
140      * @param ast the AST to get children of
141      * @return a list of all children of the given AST
142      */
143     private static List<DetailAST> getChildList(DetailAST ast) {
144         final List<DetailAST> children = new ArrayList<>();
145         DetailAST child = ast.findFirstToken(TokenTypes.OBJBLOCK).getFirstChild();
146         while (child != null) {
147             children.add(child);
148             child = child.getNextSibling();
149         }
150         return children;
151     }
152 
153     /**
154      * Check if the given AST is a constructor.
155      *
156      * @param ast the AST to check
157      * @return true if the given AST is a constructor, false otherwise
158      */
159     private static boolean isConstructor(DetailAST ast) {
160         return ast.getType() == TokenTypes.CTOR_DEF
161                 || ast.getType() == TokenTypes.COMPACT_CTOR_DEF;
162     }
163 }