001/////////////////////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code and other text files for adherence to a set of rules. 003// Copyright (C) 2001-2023 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.design; 021 022import com.puppycrawl.tools.checkstyle.StatelessCheck; 023import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 024import com.puppycrawl.tools.checkstyle.api.DetailAST; 025import com.puppycrawl.tools.checkstyle.api.TokenTypes; 026 027/** 028 * <p> 029 * Makes sure that utility classes (classes that contain only static methods or fields in their API) 030 * do not have a public constructor. 031 * </p> 032 * <p> 033 * Rationale: Instantiating utility classes does not make sense. 034 * Hence, the constructors should either be private or (if you want to allow subclassing) protected. 035 * A common mistake is forgetting to hide the default constructor. 036 * </p> 037 * <p> 038 * If you make the constructor protected you may want to consider the following constructor 039 * implementation technique to disallow instantiating subclasses: 040 * </p> 041 * <pre> 042 * public class StringUtils // not final to allow subclassing 043 * { 044 * protected StringUtils() { 045 * // prevents calls from subclass 046 * throw new UnsupportedOperationException(); 047 * } 048 * 049 * public static int count(char c, String s) { 050 * // ... 051 * } 052 * } 053 * </pre> 054 * <p> 055 * To configure the check: 056 * </p> 057 * <pre> 058 * <module name="HideUtilityClassConstructor"/> 059 * </pre> 060 * <p> 061 * Example: 062 * </p> 063 * <pre> 064 * class Test { // violation, class only has a static method and a constructor 065 * 066 * public Test() { 067 * } 068 * 069 * public static void fun() { 070 * } 071 * } 072 * 073 * class Foo { // OK 074 * 075 * private Foo() { 076 * } 077 * 078 * static int n; 079 * } 080 * 081 * class Bar { // OK 082 * 083 * protected Bar() { 084 * // prevents calls from subclass 085 * throw new UnsupportedOperationException(); 086 * } 087 * } 088 * 089 * class UtilityClass { // violation, class only has a static field 090 * 091 * static float f; 092 * } 093 * </pre> 094 * <p> 095 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker} 096 * </p> 097 * <p> 098 * Violation Message Keys: 099 * </p> 100 * <ul> 101 * <li> 102 * {@code hide.utility.class} 103 * </li> 104 * </ul> 105 * 106 * @since 3.1 107 */ 108@StatelessCheck 109public class HideUtilityClassConstructorCheck extends AbstractCheck { 110 111 /** 112 * A key is pointing to the warning message text in "messages.properties" 113 * file. 114 */ 115 public static final String MSG_KEY = "hide.utility.class"; 116 117 @Override 118 public int[] getDefaultTokens() { 119 return getRequiredTokens(); 120 } 121 122 @Override 123 public int[] getAcceptableTokens() { 124 return getRequiredTokens(); 125 } 126 127 @Override 128 public int[] getRequiredTokens() { 129 return new int[] {TokenTypes.CLASS_DEF}; 130 } 131 132 @Override 133 public void visitToken(DetailAST ast) { 134 // abstract class could not have private constructor 135 if (!isAbstract(ast)) { 136 final boolean hasStaticModifier = isStatic(ast); 137 138 final Details details = new Details(ast); 139 details.invoke(); 140 141 final boolean hasDefaultCtor = details.isHasDefaultCtor(); 142 final boolean hasPublicCtor = details.isHasPublicCtor(); 143 final boolean hasNonStaticMethodOrField = details.isHasNonStaticMethodOrField(); 144 final boolean hasNonPrivateStaticMethodOrField = 145 details.isHasNonPrivateStaticMethodOrField(); 146 147 final boolean hasAccessibleCtor = hasDefaultCtor || hasPublicCtor; 148 149 // figure out if class extends java.lang.object directly 150 // keep it simple for now and get a 99% solution 151 final boolean extendsJlo = 152 ast.findFirstToken(TokenTypes.EXTENDS_CLAUSE) == null; 153 154 final boolean isUtilClass = extendsJlo 155 && !hasNonStaticMethodOrField && hasNonPrivateStaticMethodOrField; 156 157 if (isUtilClass && hasAccessibleCtor && !hasStaticModifier) { 158 log(ast, MSG_KEY); 159 } 160 } 161 } 162 163 /** 164 * Returns true if given class is abstract or false. 165 * 166 * @param ast class definition for check. 167 * @return true if a given class declared as abstract. 168 */ 169 private static boolean isAbstract(DetailAST ast) { 170 return ast.findFirstToken(TokenTypes.MODIFIERS) 171 .findFirstToken(TokenTypes.ABSTRACT) != null; 172 } 173 174 /** 175 * Returns true if given class is static or false. 176 * 177 * @param ast class definition for check. 178 * @return true if a given class declared as static. 179 */ 180 private static boolean isStatic(DetailAST ast) { 181 return ast.findFirstToken(TokenTypes.MODIFIERS) 182 .findFirstToken(TokenTypes.LITERAL_STATIC) != null; 183 } 184 185 /** 186 * Details of class that are required for validation. 187 */ 188 private static final class Details { 189 190 /** Class ast. */ 191 private final DetailAST ast; 192 /** Result of details gathering. */ 193 private boolean hasNonStaticMethodOrField; 194 /** Result of details gathering. */ 195 private boolean hasNonPrivateStaticMethodOrField; 196 /** Result of details gathering. */ 197 private boolean hasDefaultCtor; 198 /** Result of details gathering. */ 199 private boolean hasPublicCtor; 200 201 /** 202 * C-tor. 203 * 204 * @param ast class ast 205 * */ 206 private Details(DetailAST ast) { 207 this.ast = ast; 208 } 209 210 /** 211 * Getter. 212 * 213 * @return boolean 214 */ 215 public boolean isHasNonStaticMethodOrField() { 216 return hasNonStaticMethodOrField; 217 } 218 219 /** 220 * Getter. 221 * 222 * @return boolean 223 */ 224 public boolean isHasNonPrivateStaticMethodOrField() { 225 return hasNonPrivateStaticMethodOrField; 226 } 227 228 /** 229 * Getter. 230 * 231 * @return boolean 232 */ 233 public boolean isHasDefaultCtor() { 234 return hasDefaultCtor; 235 } 236 237 /** 238 * Getter. 239 * 240 * @return boolean 241 */ 242 public boolean isHasPublicCtor() { 243 return hasPublicCtor; 244 } 245 246 /** 247 * Main method to gather statistics. 248 */ 249 public void invoke() { 250 final DetailAST objBlock = ast.findFirstToken(TokenTypes.OBJBLOCK); 251 hasDefaultCtor = true; 252 DetailAST child = objBlock.getFirstChild(); 253 254 while (child != null) { 255 final int type = child.getType(); 256 if (type == TokenTypes.METHOD_DEF 257 || type == TokenTypes.VARIABLE_DEF) { 258 final DetailAST modifiers = 259 child.findFirstToken(TokenTypes.MODIFIERS); 260 final boolean isStatic = 261 modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) != null; 262 263 if (isStatic) { 264 final boolean isPrivate = 265 modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) != null; 266 267 if (!isPrivate) { 268 hasNonPrivateStaticMethodOrField = true; 269 } 270 } 271 else { 272 hasNonStaticMethodOrField = true; 273 } 274 } 275 if (type == TokenTypes.CTOR_DEF) { 276 hasDefaultCtor = false; 277 final DetailAST modifiers = 278 child.findFirstToken(TokenTypes.MODIFIERS); 279 if (modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null 280 && modifiers.findFirstToken(TokenTypes.LITERAL_PROTECTED) == null) { 281 // treat package visible as public 282 // for the purpose of this Check 283 hasPublicCtor = true; 284 } 285 } 286 child = child.getNextSibling(); 287 } 288 } 289 290 } 291 292}