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.design; 021 022import java.util.Arrays; 023import java.util.Objects; 024import java.util.Optional; 025import java.util.Set; 026import java.util.function.Predicate; 027import java.util.regex.Matcher; 028import java.util.regex.Pattern; 029import java.util.stream.Collectors; 030 031import com.puppycrawl.tools.checkstyle.StatelessCheck; 032import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 033import com.puppycrawl.tools.checkstyle.api.DetailAST; 034import com.puppycrawl.tools.checkstyle.api.Scope; 035import com.puppycrawl.tools.checkstyle.api.TokenTypes; 036import com.puppycrawl.tools.checkstyle.utils.JavadocUtil; 037import com.puppycrawl.tools.checkstyle.utils.ScopeUtil; 038import com.puppycrawl.tools.checkstyle.utils.TokenUtil; 039 040/** 041 * <div> 042 * Checks that classes are designed for extension (subclass creation). 043 * </div> 044 * 045 * <p> 046 * Nothing wrong could be with founded classes. 047 * This check makes sense only for library projects (not application projects) 048 * which care of ideal OOP-design to make sure that class works in all cases even misusage. 049 * Even in library projects this check most likely will find classes that are designed for extension 050 * by somebody. User needs to use suppressions extensively to got a benefit from this check, 051 * and keep in suppressions all confirmed/known classes that are deigned for inheritance 052 * intentionally to let the check catch only new classes, and bring this to team/user attention. 053 * </p> 054 * 055 * <p> 056 * ATTENTION: Only user can decide whether a class is designed for extension or not. 057 * The check just shows all classes which are possibly designed for extension. 058 * If something inappropriate is found please use suppression. 059 * </p> 060 * 061 * <p> 062 * ATTENTION: If the method which can be overridden in a subclass has a javadoc comment 063 * (a good practice is to explain its self-use of overridable methods) the check will not 064 * rise a violation. The violation can also be skipped if the method which can be overridden 065 * in a subclass has one or more annotations that are specified in ignoredAnnotations 066 * option. Note, that by default @Override annotation is not included in the 067 * ignoredAnnotations set as in a subclass the method which has the annotation can also be 068 * overridden in its subclass. 069 * </p> 070 * 071 * <p> 072 * Problem is described at "Effective Java, 2nd Edition by Joshua Bloch" book, chapter 073 * "Item 17: Design and document for inheritance or else prohibit it". 074 * </p> 075 * 076 * <p> 077 * Some quotes from book: 078 * </p> 079 * <blockquote>The class must document its self-use of overridable methods. 080 * By convention, a method that invokes overridable methods contains a description 081 * of these invocations at the end of its documentation comment. The description 082 * begins with the phrase “This implementation.” 083 * </blockquote> 084 * <blockquote> 085 * The best solution to this problem is to prohibit subclassing in classes that 086 * are not designed and documented to be safely subclassed. 087 * </blockquote> 088 * <blockquote> 089 * If a concrete class does not implement a standard interface, then you may 090 * inconvenience some programmers by prohibiting inheritance. If you feel that you 091 * must allow inheritance from such a class, one reasonable approach is to ensure 092 * that the class never invokes any of its overridable methods and to document this 093 * fact. In other words, eliminate the class’s self-use of overridable methods entirely. 094 * In doing so, you’ll create a class that is reasonably safe to subclass. Overriding a 095 * method will never affect the behavior of any other method. 096 * </blockquote> 097 * 098 * <p> 099 * The check finds classes that have overridable methods (public or protected methods 100 * that are non-static, not-final, non-abstract) and have non-empty implementation. 101 * </p> 102 * 103 * <p> 104 * Rationale: This library design style protects superclasses against being broken 105 * by subclasses. The downside is that subclasses are limited in their flexibility, 106 * in particular they cannot prevent execution of code in the superclass, but that 107 * also means that subclasses cannot corrupt the state of the superclass by forgetting 108 * to call the superclass's method. 109 * </p> 110 * 111 * <p> 112 * More specifically, it enforces a programming style where superclasses provide 113 * empty "hooks" that can be implemented by subclasses. 114 * </p> 115 * 116 * <p> 117 * Example of code that cause violation as it is designed for extension: 118 * </p> 119 * {@snippet lang="text" : 120 * public abstract class Plant { 121 * private String roots; 122 * private String trunk; 123 * 124 * protected void validate() { 125 * if (roots == null) throw new IllegalArgumentException("No roots!"); 126 * if (trunk == null) throw new IllegalArgumentException("No trunk!"); 127 * } 128 * 129 * public abstract void grow(); 130 * } 131 * 132 * public class Tree extends Plant { 133 * private List leaves; 134 * 135 * @Overrides 136 * protected void validate() { 137 * super.validate(); 138 * if (leaves == null) throw new IllegalArgumentException("No leaves!"); 139 * } 140 * 141 * public void grow() { 142 * validate(); 143 * } 144 * } 145 * } 146 * 147 * <p> 148 * Example of code without violation: 149 * </p> 150 * {@snippet lang="text" : 151 * public abstract class Plant { 152 * private String roots; 153 * private String trunk; 154 * 155 * private void validate() { 156 * if (roots == null) throw new IllegalArgumentException("No roots!"); 157 * if (trunk == null) throw new IllegalArgumentException("No trunk!"); 158 * validateEx(); 159 * } 160 * 161 * protected void validateEx() { } 162 * 163 * public abstract void grow(); 164 * } 165 * } 166 * 167 * @since 3.1 168 */ 169@StatelessCheck 170public class DesignForExtensionCheck extends AbstractCheck { 171 172 /** 173 * A key is pointing to the warning message text in "messages.properties" file. 174 */ 175 public static final String MSG_KEY = "design.forExtension"; 176 177 /** 178 * Specify annotations which allow the check to skip the method from validation. 179 */ 180 private Set<String> ignoredAnnotations = Arrays.stream(new String[] {"Test", "Before", "After", 181 "BeforeClass", "AfterClass", }).collect(Collectors.toUnmodifiableSet()); 182 183 /** 184 * Specify the comment text pattern which qualifies a method as designed for extension. 185 * Supports multi-line regex. 186 */ 187 private Pattern requiredJavadocPhrase = Pattern.compile(".*"); 188 189 /** 190 * Creates a new {@code DesignForExtensionCheck} instance. 191 */ 192 public DesignForExtensionCheck() { 193 // no code by default 194 } 195 196 /** 197 * Setter to specify annotations which allow the check to skip the method from validation. 198 * 199 * @param ignoredAnnotations method annotations. 200 * @since 7.2 201 */ 202 public void setIgnoredAnnotations(String... ignoredAnnotations) { 203 this.ignoredAnnotations = Arrays.stream(ignoredAnnotations) 204 .collect(Collectors.toUnmodifiableSet()); 205 } 206 207 /** 208 * Setter to specify the comment text pattern which qualifies a 209 * method as designed for extension. Supports multi-line regex. 210 * 211 * @param requiredJavadocPhrase method annotations. 212 * @since 8.40 213 */ 214 public void setRequiredJavadocPhrase(Pattern requiredJavadocPhrase) { 215 this.requiredJavadocPhrase = requiredJavadocPhrase; 216 } 217 218 @Override 219 public int[] getDefaultTokens() { 220 return getRequiredTokens(); 221 } 222 223 @Override 224 public int[] getAcceptableTokens() { 225 return getRequiredTokens(); 226 } 227 228 @Override 229 public int[] getRequiredTokens() { 230 // The check does not subscribe to CLASS_DEF token as now it is stateless. If the check 231 // subscribes to CLASS_DEF token it will become stateful, since we need to have additional 232 // stack to hold CLASS_DEF tokens. 233 return new int[] {TokenTypes.METHOD_DEF}; 234 } 235 236 @Override 237 public boolean isCommentNodesRequired() { 238 return true; 239 } 240 241 @Override 242 public void visitToken(DetailAST ast) { 243 if (!hasJavadocComment(ast) 244 && canBeOverridden(ast) 245 && (isNativeMethod(ast) 246 || !hasEmptyImplementation(ast)) 247 && !hasIgnoredAnnotation(ast, ignoredAnnotations) 248 && !ScopeUtil.isInRecordBlock(ast)) { 249 final DetailAST classDef = getNearestClassOrEnumDefinition(ast); 250 if (canBeSubclassed(classDef)) { 251 final String className = classDef.findFirstToken(TokenTypes.IDENT).getText(); 252 final String methodName = ast.findFirstToken(TokenTypes.IDENT).getText(); 253 log(ast, MSG_KEY, className, methodName); 254 } 255 } 256 } 257 258 /** 259 * Checks whether a method has a javadoc comment. 260 * 261 * @param methodDef method definition token. 262 * @return true if a method has a javadoc comment. 263 */ 264 private boolean hasJavadocComment(DetailAST methodDef) { 265 return hasJavadocCommentOnToken(methodDef, TokenTypes.MODIFIERS) 266 || hasJavadocCommentOnToken(methodDef, TokenTypes.TYPE); 267 } 268 269 /** 270 * Checks whether a token has a javadoc comment. 271 * 272 * @param methodDef method definition token. 273 * @param tokenType token type. 274 * @return true if a token has a javadoc comment. 275 */ 276 private boolean hasJavadocCommentOnToken(DetailAST methodDef, int tokenType) { 277 final DetailAST token = methodDef.findFirstToken(tokenType); 278 return branchContainsJavadocComment(token); 279 } 280 281 /** 282 * Checks whether a javadoc comment exists under the token. 283 * 284 * @param token tree token. 285 * @return true if a javadoc comment exists under the token. 286 */ 287 private boolean branchContainsJavadocComment(DetailAST token) { 288 boolean result = false; 289 DetailAST curNode = token; 290 while (curNode != null) { 291 if (curNode.getType() == TokenTypes.BLOCK_COMMENT_BEGIN 292 && JavadocUtil.isJavadocComment(curNode)) { 293 result = hasValidJavadocComment(curNode); 294 break; 295 } 296 297 DetailAST toVisit = curNode.getFirstChild(); 298 while (toVisit == null) { 299 if (curNode == token) { 300 break; 301 } 302 303 toVisit = curNode.getNextSibling(); 304 curNode = curNode.getParent(); 305 } 306 curNode = toVisit; 307 } 308 309 return result; 310 } 311 312 /** 313 * Checks whether a javadoc contains the specified comment pattern that denotes 314 * a method as designed for extension. 315 * 316 * @param detailAST the ast we are checking for possible extension 317 * @return true if the javadoc of this ast contains the required comment pattern 318 */ 319 private boolean hasValidJavadocComment(DetailAST detailAST) { 320 final String javadocString = 321 JavadocUtil.getBlockCommentContent(detailAST); 322 323 final Matcher requiredJavadocPhraseMatcher = 324 requiredJavadocPhrase.matcher(javadocString); 325 326 return requiredJavadocPhraseMatcher.find(); 327 } 328 329 /** 330 * Checks whether a method is native. 331 * 332 * @param ast method definition token. 333 * @return true if a methods is native. 334 */ 335 private static boolean isNativeMethod(DetailAST ast) { 336 final DetailAST mods = ast.findFirstToken(TokenTypes.MODIFIERS); 337 return mods.findFirstToken(TokenTypes.LITERAL_NATIVE) != null; 338 } 339 340 /** 341 * Checks whether a method has only comments in the body (has an empty implementation). 342 * Method is OK if its implementation is empty. 343 * 344 * @param ast method definition token. 345 * @return true if a method has only comments in the body. 346 */ 347 private static boolean hasEmptyImplementation(DetailAST ast) { 348 boolean hasEmptyBody = true; 349 final DetailAST methodImplOpenBrace = ast.findFirstToken(TokenTypes.SLIST); 350 final DetailAST methodImplCloseBrace = methodImplOpenBrace.getLastChild(); 351 final Predicate<DetailAST> predicate = currentNode -> { 352 return currentNode != methodImplCloseBrace 353 && !TokenUtil.isCommentType(currentNode.getType()); 354 }; 355 final Optional<DetailAST> methodBody = 356 TokenUtil.findFirstTokenByPredicate(methodImplOpenBrace, predicate); 357 if (methodBody.isPresent()) { 358 hasEmptyBody = false; 359 } 360 return hasEmptyBody; 361 } 362 363 /** 364 * Checks whether a method can be overridden. 365 * Method can be overridden if it is not private, abstract, final or static. 366 * Note that the check has nothing to do for interfaces. 367 * 368 * @param methodDef method definition token. 369 * @return true if a method can be overridden in a subclass. 370 */ 371 private static boolean canBeOverridden(DetailAST methodDef) { 372 final DetailAST modifiers = methodDef.findFirstToken(TokenTypes.MODIFIERS); 373 return ScopeUtil.getSurroundingScope(methodDef) 374 .map(surroundingScope -> { 375 return surroundingScope.isIn(Scope.PROTECTED) 376 && !ScopeUtil.isInInterfaceOrAnnotationBlock(methodDef) 377 && modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null 378 && modifiers.findFirstToken(TokenTypes.ABSTRACT) == null 379 && modifiers.findFirstToken(TokenTypes.FINAL) == null 380 && modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) == null; 381 }) 382 .orElse(Boolean.FALSE); 383 } 384 385 /** 386 * Checks whether a method has any of ignored annotations. 387 * 388 * @param methodDef method definition token. 389 * @param annotations a set of ignored annotations. 390 * @return true if a method has any of ignored annotations. 391 */ 392 private static boolean hasIgnoredAnnotation(DetailAST methodDef, Set<String> annotations) { 393 final DetailAST modifiers = methodDef.findFirstToken(TokenTypes.MODIFIERS); 394 final Optional<DetailAST> annotation = TokenUtil.findFirstTokenByPredicate(modifiers, 395 currentToken -> { 396 return currentToken.getType() == TokenTypes.ANNOTATION 397 && annotations.contains(getAnnotationName(currentToken)); 398 }); 399 return annotation.isPresent(); 400 } 401 402 /** 403 * Gets the name of the annotation. 404 * 405 * @param annotation to get name of. 406 * @return the name of the annotation. 407 */ 408 private static String getAnnotationName(DetailAST annotation) { 409 final DetailAST dotAst = annotation.findFirstToken(TokenTypes.DOT); 410 final DetailAST parent = Objects.requireNonNullElse(dotAst, annotation); 411 return parent.findFirstToken(TokenTypes.IDENT).getText(); 412 } 413 414 /** 415 * Returns CLASS_DEF or ENUM_DEF token which is the nearest to the given ast node. 416 * Searches the tree towards the root until it finds a CLASS_DEF or ENUM_DEF node. 417 * 418 * @param ast the start node for searching. 419 * @return the CLASS_DEF or ENUM_DEF token. 420 */ 421 private static DetailAST getNearestClassOrEnumDefinition(DetailAST ast) { 422 DetailAST searchAST = ast; 423 while (searchAST.getType() != TokenTypes.CLASS_DEF 424 && searchAST.getType() != TokenTypes.ENUM_DEF) { 425 searchAST = searchAST.getParent(); 426 } 427 return searchAST; 428 } 429 430 /** 431 * Checks if the given class (given CLASS_DEF node) can be subclassed. 432 * 433 * @param classDef class definition token. 434 * @return true if the containing class can be subclassed. 435 */ 436 private static boolean canBeSubclassed(DetailAST classDef) { 437 final DetailAST modifiers = classDef.findFirstToken(TokenTypes.MODIFIERS); 438 return classDef.getType() != TokenTypes.ENUM_DEF 439 && modifiers.findFirstToken(TokenTypes.FINAL) == null 440 && hasDefaultOrExplicitNonPrivateCtor(classDef); 441 } 442 443 /** 444 * Checks whether a class has default or explicit non-private constructor. 445 * 446 * @param classDef class ast token. 447 * @return true if a class has default or explicit non-private constructor. 448 */ 449 private static boolean hasDefaultOrExplicitNonPrivateCtor(DetailAST classDef) { 450 // check if subclassing is prevented by having only private ctors 451 final DetailAST objBlock = classDef.findFirstToken(TokenTypes.OBJBLOCK); 452 453 boolean hasDefaultConstructor = true; 454 boolean hasExplicitNonPrivateCtor = false; 455 456 DetailAST candidate = objBlock.getFirstChild(); 457 458 while (candidate != null) { 459 if (candidate.getType() == TokenTypes.CTOR_DEF) { 460 hasDefaultConstructor = false; 461 462 final DetailAST ctorMods = 463 candidate.findFirstToken(TokenTypes.MODIFIERS); 464 if (ctorMods.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null) { 465 hasExplicitNonPrivateCtor = true; 466 break; 467 } 468 } 469 candidate = candidate.getNextSibling(); 470 } 471 472 return hasDefaultConstructor || hasExplicitNonPrivateCtor; 473 } 474 475}