001/////////////////////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code and other text files for adherence to a set of rules. 003// Copyright (C) 2001-2026 the original author or authors. 004// 005// This library is free software; you can redistribute it and/or 006// modify it under the terms of the GNU Lesser General Public 007// License as published by the Free Software Foundation; either 008// version 2.1 of the License, or (at your option) any later version. 009// 010// This library is distributed in the hope that it will be useful, 011// but WITHOUT ANY WARRANTY; without even the implied warranty of 012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 013// Lesser General Public License for more details. 014// 015// You should have received a copy of the GNU Lesser General Public 016// License along with this library; if not, write to the Free Software 017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 018/////////////////////////////////////////////////////////////////////////////////////////////// 019 020package com.puppycrawl.tools.checkstyle.checks.coding; 021 022import java.util.ArrayList; 023import java.util.List; 024import java.util.Optional; 025 026import com.puppycrawl.tools.checkstyle.StatelessCheck; 027import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 028import com.puppycrawl.tools.checkstyle.api.DetailAST; 029import com.puppycrawl.tools.checkstyle.api.TokenTypes; 030 031/** 032 * <div> 033 * Checks that all constructors are grouped together. 034 * If there is any non-constructor code separating constructors, 035 * this check identifies and logs a violation for those ungrouped constructors. 036 * The violation message will specify the line number of the last grouped constructor. 037 * Comments between constructors are allowed. 038 * </div> 039 * 040 * <p> 041 * Rationale: Grouping constructors together in a class improves code readability 042 * and maintainability. It allows developers to easily understand 043 * the different ways an object can be instantiated 044 * and the tasks performed by each constructor. 045 * </p> 046 * 047 * @since 10.17.0 048 */ 049 050@StatelessCheck 051public class ConstructorsDeclarationGroupingCheck extends AbstractCheck { 052 053 /** 054 * A key is pointing to the warning message text in "messages.properties" 055 * file. 056 */ 057 public static final String MSG_KEY = "constructors.declaration.grouping"; 058 059 /** 060 * A key is pointing to the warning message text in "messages.properties" 061 * file. 062 */ 063 public static final String MSG_ORDER = "constructors.declaration.order"; 064 065 /** 066 * Control whether to order constructors by increasing arity. 067 */ 068 private boolean orderByIncreasingArity; 069 070 /** 071 * Setter to control whether to enforce order by increasing arity or not. 072 * 073 * @param orderByIncreasingArity true if order by increasing arity is required. 074 * @since 13.5.0 075 */ 076 public void setOrderByIncreasingArity(boolean orderByIncreasingArity) { 077 this.orderByIncreasingArity = orderByIncreasingArity; 078 } 079 080 @Override 081 public int[] getDefaultTokens() { 082 return getRequiredTokens(); 083 } 084 085 @Override 086 public int[] getAcceptableTokens() { 087 return getRequiredTokens(); 088 } 089 090 @Override 091 public int[] getRequiredTokens() { 092 return new int[] { 093 TokenTypes.CLASS_DEF, 094 TokenTypes.ENUM_DEF, 095 TokenTypes.RECORD_DEF, 096 }; 097 } 098 099 @Override 100 public void visitToken(DetailAST ast) { 101 // list of all child ASTs 102 final List<DetailAST> children = getChildList(ast); 103 104 // find first constructor 105 final DetailAST firstConstructor = children.stream() 106 .filter(ConstructorsDeclarationGroupingCheck::isConstructor) 107 .findFirst() 108 .orElse(null); 109 110 if (firstConstructor != null) { 111 112 // get all children AST after the first constructor 113 final List<DetailAST> childrenAfterFirstConstructor = 114 children.subList(children.indexOf(firstConstructor), children.size()); 115 116 // find the first index of non-constructor AST after the first constructor, if present 117 final Optional<Integer> indexOfFirstNonConstructor = childrenAfterFirstConstructor 118 .stream() 119 .filter(currAst -> !isConstructor(currAst)) 120 .findFirst() 121 .map(children::indexOf); 122 123 // list of all children after first non-constructor AST 124 final List<DetailAST> childrenAfterFirstNonConstructor = indexOfFirstNonConstructor 125 .map(index -> children.subList(index, children.size())) 126 .orElseGet(ArrayList::new); 127 128 // create a list of all constructors that are not grouped to log 129 final List<DetailAST> constructorsToLog = childrenAfterFirstNonConstructor.stream() 130 .filter(ConstructorsDeclarationGroupingCheck::isConstructor) 131 .toList(); 132 133 // find the last grouped constructor 134 final DetailAST lastGroupedConstructor = childrenAfterFirstConstructor.stream() 135 .takeWhile(ConstructorsDeclarationGroupingCheck::isConstructor) 136 .reduce((first, second) -> second) 137 .orElse(firstConstructor); 138 139 // log all constructors that are not grouped 140 constructorsToLog 141 .forEach(ctor -> log(ctor, MSG_KEY, lastGroupedConstructor.getLineNo())); 142 143 if (orderByIncreasingArity) { 144 145 // list of all constructor ASTs 146 final List<DetailAST> allConstructors = children.stream() 147 .filter(ConstructorsDeclarationGroupingCheck::isConstructor) 148 .toList(); 149 150 int previousParamCount = 0; 151 boolean isOrdered = true; 152 for (DetailAST constructor : allConstructors) { 153 final int currentParamCount = getArity(constructor); 154 isOrdered = isOrdered && currentParamCount >= previousParamCount; 155 previousParamCount = currentParamCount; 156 if (!isOrdered) { 157 log(constructor, MSG_ORDER); 158 } 159 } 160 } 161 } 162 } 163 164 /** 165 * Get a list of all children of the given AST. 166 * 167 * @param ast the AST to get children of 168 * @return a list of all children of the given AST 169 */ 170 private static List<DetailAST> getChildList(DetailAST ast) { 171 final List<DetailAST> children = new ArrayList<>(); 172 DetailAST child = ast.findFirstToken(TokenTypes.OBJBLOCK).getFirstChild(); 173 while (child != null) { 174 children.add(child); 175 child = child.getNextSibling(); 176 } 177 return children; 178 } 179 180 /** 181 * Check if the given AST is a constructor. 182 * 183 * @param ast the AST to check 184 * @return true if the given AST is a constructor, false otherwise 185 */ 186 private static boolean isConstructor(DetailAST ast) { 187 return ast.getType() == TokenTypes.CTOR_DEF 188 || ast.getType() == TokenTypes.COMPACT_CTOR_DEF; 189 } 190 191 /** 192 * Get the arity of a constructor. 193 * 194 * @param constructor the constructor AST 195 * @return the arity of the constructor 196 */ 197 private static int getArity(DetailAST constructor) { 198 final DetailAST params = constructor.findFirstToken(TokenTypes.PARAMETERS); 199 int arity = 0; 200 if (params != null) { 201 arity = params.getChildCount(TokenTypes.PARAMETER_DEF); 202 } 203 return arity; 204 } 205}