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  import java.util.stream.Collectors;
26  
27  import com.puppycrawl.tools.checkstyle.StatelessCheck;
28  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
29  import com.puppycrawl.tools.checkstyle.api.DetailAST;
30  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
31  
32  /**
33   * <div>
34   * Checks that all constructors are grouped together.
35   * If there is any non-constructor code separating constructors,
36   * this check identifies and logs a violation for those ungrouped constructors.
37   * The violation message will specify the line number of the last grouped constructor.
38   * Comments between constructors are allowed.
39   * </div>
40   *
41   * <p>
42   * Rationale: Grouping constructors together in a class improves code readability
43   * and maintainability. It allows developers to easily understand
44   * the different ways an object can be instantiated
45   * and the tasks performed by each constructor.
46   * </p>
47   *
48   * <p>
49   * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
50   * </p>
51   *
52   * <p>
53   * Violation Message Keys:
54   * </p>
55   * <ul>
56   * <li>
57   * {@code constructors.declaration.grouping}
58   * </li>
59   * </ul>
60   *
61   * @since 10.17.0
62   */
63  
64  @StatelessCheck
65  public class ConstructorsDeclarationGroupingCheck extends AbstractCheck {
66  
67      /**
68       * A key is pointing to the warning message text in "messages.properties"
69       * file.
70       */
71      public static final String MSG_KEY = "constructors.declaration.grouping";
72  
73      @Override
74      public int[] getDefaultTokens() {
75          return getRequiredTokens();
76      }
77  
78      @Override
79      public int[] getAcceptableTokens() {
80          return getRequiredTokens();
81      }
82  
83      @Override
84      public int[] getRequiredTokens() {
85          return new int[] {
86              TokenTypes.CLASS_DEF,
87              TokenTypes.ENUM_DEF,
88              TokenTypes.RECORD_DEF,
89          };
90      }
91  
92      @Override
93      public void visitToken(DetailAST ast) {
94          // list of all child ASTs
95          final List<DetailAST> children = getChildList(ast);
96  
97          // find first constructor
98          final DetailAST firstConstructor = children.stream()
99                  .filter(ConstructorsDeclarationGroupingCheck::isConstructor)
100                 .findFirst()
101                 .orElse(null);
102 
103         if (firstConstructor != null) {
104 
105             // get all children AST after the first constructor
106             final List<DetailAST> childrenAfterFirstConstructor =
107                     children.subList(children.indexOf(firstConstructor), children.size());
108 
109             // find the first index of non-constructor AST after the first constructor, if present
110             final Optional<Integer> indexOfFirstNonConstructor = childrenAfterFirstConstructor
111                     .stream()
112                     .filter(currAst -> !isConstructor(currAst))
113                     .findFirst()
114                     .map(children::indexOf);
115 
116             // list of all children after first non-constructor AST
117             final List<DetailAST> childrenAfterFirstNonConstructor = indexOfFirstNonConstructor
118                     .map(index -> children.subList(index, children.size()))
119                     .orElseGet(ArrayList::new);
120 
121             // create a list of all constructors that are not grouped to log
122             final List<DetailAST> constructorsToLog = childrenAfterFirstNonConstructor.stream()
123                     .filter(ConstructorsDeclarationGroupingCheck::isConstructor)
124                     .collect(Collectors.toUnmodifiableList());
125 
126             // find the last grouped constructor
127             final DetailAST lastGroupedConstructor = childrenAfterFirstConstructor.stream()
128                     .takeWhile(ConstructorsDeclarationGroupingCheck::isConstructor)
129                     .reduce((first, second) -> second)
130                     .orElse(firstConstructor);
131 
132             // log all constructors that are not grouped
133             constructorsToLog
134                     .forEach(ctor -> log(ctor, MSG_KEY, lastGroupedConstructor.getLineNo()));
135         }
136     }
137 
138     /**
139      * Get a list of all children of the given AST.
140      *
141      * @param ast the AST to get children of
142      * @return a list of all children of the given AST
143      */
144     private static List<DetailAST> getChildList(DetailAST ast) {
145         final List<DetailAST> children = new ArrayList<>();
146         DetailAST child = ast.findFirstToken(TokenTypes.OBJBLOCK).getFirstChild();
147         while (child != null) {
148             children.add(child);
149             child = child.getNextSibling();
150         }
151         return children;
152     }
153 
154     /**
155      * Check if the given AST is a constructor.
156      *
157      * @param ast the AST to check
158      * @return true if the given AST is a constructor, false otherwise
159      */
160     private static boolean isConstructor(DetailAST ast) {
161         return ast.getType() == TokenTypes.CTOR_DEF
162                 || ast.getType() == TokenTypes.COMPACT_CTOR_DEF;
163     }
164 }