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