1 ///////////////////////////////////////////////////////////////////////////////////////////////
2 // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3 // Copyright (C) 2001-2024 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 * <p>
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 * </p>
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 * <p>
47 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
48 * </p>
49 * <p>
50 * Violation Message Keys:
51 * </p>
52 * <ul>
53 * <li>
54 * {@code constructors.declaration.grouping}
55 * </li>
56 * </ul>
57 *
58 * @since 10.17.0
59 */
60
61 @StatelessCheck
62 public class ConstructorsDeclarationGroupingCheck extends AbstractCheck {
63
64 /**
65 * A key is pointing to the warning message text in "messages.properties"
66 * file.
67 */
68 public static final String MSG_KEY = "constructors.declaration.grouping";
69
70 @Override
71 public int[] getDefaultTokens() {
72 return getRequiredTokens();
73 }
74
75 @Override
76 public int[] getAcceptableTokens() {
77 return getRequiredTokens();
78 }
79
80 @Override
81 public int[] getRequiredTokens() {
82 return new int[] {
83 TokenTypes.CLASS_DEF,
84 TokenTypes.ENUM_DEF,
85 TokenTypes.RECORD_DEF,
86 };
87 }
88
89 @Override
90 public void visitToken(DetailAST ast) {
91 // list of all child ASTs
92 final List<DetailAST> children = getChildList(ast);
93
94 // find first constructor
95 final DetailAST firstConstructor = children.stream()
96 .filter(ConstructorsDeclarationGroupingCheck::isConstructor)
97 .findFirst()
98 .orElse(null);
99
100 if (firstConstructor != null) {
101
102 // get all children AST after the first constructor
103 final List<DetailAST> childrenAfterFirstConstructor =
104 children.subList(children.indexOf(firstConstructor), children.size());
105
106 // find the first index of non-constructor AST after the first constructor, if present
107 final Optional<Integer> indexOfFirstNonConstructor = childrenAfterFirstConstructor
108 .stream()
109 .filter(currAst -> !isConstructor(currAst))
110 .findFirst()
111 .map(children::indexOf);
112
113 // list of all children after first non-constructor AST
114 final List<DetailAST> childrenAfterFirstNonConstructor = indexOfFirstNonConstructor
115 .map(index -> children.subList(index, children.size()))
116 .orElseGet(ArrayList::new);
117
118 // create a list of all constructors that are not grouped to log
119 final List<DetailAST> constructorsToLog = childrenAfterFirstNonConstructor.stream()
120 .filter(ConstructorsDeclarationGroupingCheck::isConstructor)
121 .collect(Collectors.toUnmodifiableList());
122
123 // find the last grouped constructor
124 final DetailAST lastGroupedConstructor = childrenAfterFirstConstructor.stream()
125 .takeWhile(ConstructorsDeclarationGroupingCheck::isConstructor)
126 .reduce((first, second) -> second)
127 .orElse(firstConstructor);
128
129 // log all constructors that are not grouped
130 constructorsToLog
131 .forEach(ctor -> log(ctor, MSG_KEY, lastGroupedConstructor.getLineNo()));
132 }
133 }
134
135 /**
136 * Get a list of all children of the given AST.
137 *
138 * @param ast the AST to get children of
139 * @return a list of all children of the given AST
140 */
141 private static List<DetailAST> getChildList(DetailAST ast) {
142 final List<DetailAST> children = new ArrayList<>();
143 DetailAST child = ast.findFirstToken(TokenTypes.OBJBLOCK).getFirstChild();
144 while (child != null) {
145 children.add(child);
146 child = child.getNextSibling();
147 }
148 return children;
149 }
150
151 /**
152 * Check if the given AST is a constructor.
153 *
154 * @param ast the AST to check
155 * @return true if the given AST is a constructor, false otherwise
156 */
157 private static boolean isConstructor(DetailAST ast) {
158 return ast.getType() == TokenTypes.CTOR_DEF
159 || ast.getType() == TokenTypes.COMPACT_CTOR_DEF;
160 }
161 }