public class DesignForExtensionCheck extends AbstractCheck
Checks that classes are designed for extension (subclass creation).
Nothing wrong could be with founded classes. This check makes sense only for library projects (not application projects) which care of ideal OOP-design to make sure that class works in all cases even misusage. Even in library projects this check most likely will find classes that are designed for extension by somebody. User needs to use suppressions extensively to got a benefit from this check, and keep in suppressions all confirmed/known classes that are deigned for inheritance intentionally to let the check catch only new classes, and bring this to team/user attention.
ATTENTION: Only user can decide whether a class is designed for extension or not. The check just shows all classes which are possibly designed for extension. If smth inappropriate is found please use suppression.
ATTENTION: If the method which can be overridden in a subclass has a javadoc comment (a good practice is to explain its self-use of overridable methods) the check will not rise a violation. The violation can also be skipped if the method which can be overridden in a subclass has one or more annotations that are specified in ignoredAnnotations option. Note, that by default @Override annotation is not included in the ignoredAnnotations set as in a subclass the method which has the annotation can also be overridden in its subclass.
Problem is described at "Effective Java, 2nd Edition by Joshua Bloch" book, chapter "Item 17: Design and document for inheritance or else prohibit it".
Some quotes from book:
The class must document its self-use of overridable methods. By convention, a method that invokes overridable methods contains a description of these invocations at the end of its documentation comment. The description begins with the phrase “This implementation.”
The best solution to this problem is to prohibit subclassing in classes that are not designed and documented to be safely subclassed.
If a concrete class does not implement a standard interface, then you may inconvenience some programmers by prohibiting inheritance. If you feel that you must allow inheritance from such a class, one reasonable approach is to ensure that the class never invokes any of its overridable methods and to document this fact. In other words, eliminate the class’s self-use of overridable methods entirely. In doing so, you’ll create a class that is reasonably safe to subclass. Overriding a method will never affect the behavior of any other method.
The check finds classes that have overridable methods (public or protected methods that are non-static, not-final, non-abstract) and have non-empty implementation.
Rationale: This library design style protects superclasses against being broken by subclasses. The downside is that subclasses are limited in their flexibility, in particular they cannot prevent execution of code in the superclass, but that also means that subclasses cannot corrupt the state of the superclass by forgetting to call the superclass's method.
More specifically, it enforces a programming style where superclasses provide empty "hooks" that can be implemented by subclasses.
Example of code that cause violation as it is designed for extension:
public abstract class Plant {
private String roots;
private String trunk;
protected void validate() {
if (roots == null) throw new IllegalArgumentException("No roots!");
if (trunk == null) throw new IllegalArgumentException("No trunk!");
}
public abstract void grow();
}
public class Tree extends Plant {
private List leaves;
@Overrides
protected void validate() {
super.validate();
if (leaves == null) throw new IllegalArgumentException("No leaves!");
}
public void grow() {
validate();
}
}
Example of code without violation:
public abstract class Plant {
private String roots;
private String trunk;
private void validate() {
if (roots == null) throw new IllegalArgumentException("No roots!");
if (trunk == null) throw new IllegalArgumentException("No trunk!");
validateEx();
}
protected void validateEx() { }
public abstract void grow();
}
ignoredAnnotations - Specify annotations which allow the check to
skip the method from validation.
Type is java.lang.String[].
Default value is After, AfterClass, Before, BeforeClass, Test.
requiredJavadocPhrase - Specify the comment text pattern which qualifies a
method as designed for extension. Supports multi-line regex.
Type is java.util.regex.Pattern.
Default value is ".*".
To configure the check:
<module name="DesignForExtension"/>
To configure the check to allow methods which have @Override and @Test annotations to be designed for extension.
<module name="DesignForExtension"> <property name="ignoredAnnotations" value="Override, Test"/> </module>
public class A {
@Override
public int foo() {
return 2;
}
public int foo2() {return 8;} // violation
}
public class B {
/**
* This implementation ...
@return some int value.
*/
public int foo() {
return 1;
}
public int foo3() {return 3;} // violation
}
public class FooTest {
@Test
public void testFoo() {
final B b = new A();
assertEquals(2, b.foo());
}
public int foo4() {return 4;} // violation
}
To configure the check to allow methods which contain a specified comment text pattern in their javadoc to be designed for extension.
<module name="DesignForExtension">
<property name="requiredJavadocPhrase"
value="This implementation"/>
</module>
public class A {
/**
* This implementation ...
*/
public int foo() {return 2;} // ok, required javadoc phrase in comment
/**
* Do not extend ...
*/
public int foo2() {return 8;} // violation, required javadoc phrase not in comment
public int foo3() {return 3;} // violation, required javadoc phrase not in comment
}
To configure the check to allow methods which contain a specified comment text pattern in their javadoc which can span multiple lines to be designed for extension.
<module name="DesignForExtension">
<property name="requiredJavadocPhrase"
value="This[\s\S]*implementation"/>
</module>
public class A {
/**
* This
* implementation ...
*/
public int foo() {return 2;} // ok, required javadoc phrase in comment
/**
* Do not extend ...
*/
public int foo2() {return 8;} // violation, required javadoc phrase not in comment
public int foo3() {return 3;} // violation, required javadoc phrase not in comment
}
Parent is com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
design.forExtension
AutomaticBean.OutputStreamOptions| Modifier and Type | Field and Description |
|---|---|
private java.util.Set<java.lang.String> |
ignoredAnnotations
Specify annotations which allow the check to skip the method from validation.
|
static java.lang.String |
MSG_KEY
A key is pointing to the warning message text in "messages.properties"
file.
|
private java.util.regex.Pattern |
requiredJavadocPhrase
Specify the comment text pattern which qualifies a method as designed for extension.
|
| Constructor and Description |
|---|
DesignForExtensionCheck() |
| Modifier and Type | Method and Description |
|---|---|
private boolean |
branchContainsJavadocComment(DetailAST token)
Checks whether a javadoc comment exists under the token.
|
private static boolean |
canBeOverridden(DetailAST methodDef)
Checks whether a method can be overridden.
|
private static boolean |
canBeSubclassed(DetailAST classDef)
Checks if the given class (given CLASS_DEF node) can be subclassed.
|
int[] |
getAcceptableTokens()
The configurable token set.
|
private static java.lang.String |
getAnnotationName(DetailAST annotation)
Gets the name of the annotation.
|
int[] |
getDefaultTokens()
Returns the default token a check is interested in.
|
private static DetailAST |
getNearestClassOrEnumDefinition(DetailAST ast)
Returns CLASS_DEF or ENUM_DEF token which is the nearest to the given ast node.
|
int[] |
getRequiredTokens()
The tokens that this check must be registered for.
|
private static boolean |
hasDefaultOrExplicitNonPrivateCtor(DetailAST classDef)
Checks whether a class has default or explicit non-private constructor.
|
private static boolean |
hasEmptyImplementation(DetailAST ast)
Checks whether a method has only comments in the body (has an empty implementation).
|
private static boolean |
hasIgnoredAnnotation(DetailAST methodDef,
java.util.Set<java.lang.String> annotations)
Checks whether a method has any of ignored annotations.
|
private boolean |
hasJavadocComment(DetailAST methodDef)
Checks whether a method has a javadoc comment.
|
private boolean |
hasJavadocCommentOnToken(DetailAST methodDef,
int tokenType)
Checks whether a token has a javadoc comment.
|
private boolean |
hasValidJavadocComment(DetailAST detailAST)
Checks whether a javadoc contains the specified comment pattern that denotes
a method as designed for extension.
|
boolean |
isCommentNodesRequired()
Whether comment nodes are required or not.
|
private static boolean |
isNativeMethod(DetailAST ast)
Checks whether a methods is native.
|
void |
setIgnoredAnnotations(java.lang.String... ignoredAnnotations)
Setter to specify annotations which allow the check to skip the method from validation.
|
void |
setRequiredJavadocPhrase(java.util.regex.Pattern requiredJavadocPhrase)
Setter to specify the comment text pattern which qualifies a
method as designed for extension.
|
void |
visitToken(DetailAST ast)
Called to process a token.
|
beginTree, clearViolations, destroy, finishTree, getFileContents, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, leaveToken, log, log, log, setFileContents, setTabWidth, setTokensfinishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverityconfigure, contextualize, getConfiguration, setupChildpublic static final java.lang.String MSG_KEY
private java.util.Set<java.lang.String> ignoredAnnotations
private java.util.regex.Pattern requiredJavadocPhrase
public DesignForExtensionCheck()
public void setIgnoredAnnotations(java.lang.String... ignoredAnnotations)
ignoredAnnotations - method annotations.public void setRequiredJavadocPhrase(java.util.regex.Pattern requiredJavadocPhrase)
requiredJavadocPhrase - method annotations.public int[] getDefaultTokens()
AbstractCheckgetDefaultTokens in class AbstractCheckTokenTypespublic int[] getAcceptableTokens()
AbstractCheckgetAcceptableTokens in class AbstractCheckTokenTypespublic int[] getRequiredTokens()
AbstractCheckgetRequiredTokens in class AbstractCheckTokenTypespublic boolean isCommentNodesRequired()
AbstractCheckisCommentNodesRequired in class AbstractCheckpublic void visitToken(DetailAST ast)
AbstractCheckvisitToken in class AbstractCheckast - the token to processprivate boolean hasJavadocComment(DetailAST methodDef)
methodDef - method definition token.private boolean hasJavadocCommentOnToken(DetailAST methodDef, int tokenType)
methodDef - method definition token.tokenType - token type.private boolean branchContainsJavadocComment(DetailAST token)
token - tree token.private boolean hasValidJavadocComment(DetailAST detailAST)
detailAST - the ast we are checking for possible extensionprivate static boolean isNativeMethod(DetailAST ast)
ast - method definition token.private static boolean hasEmptyImplementation(DetailAST ast)
ast - method definition token.private static boolean canBeOverridden(DetailAST methodDef)
methodDef - method definition token.private static boolean hasIgnoredAnnotation(DetailAST methodDef, java.util.Set<java.lang.String> annotations)
methodDef - method definition token.annotations - a set of ignored annotations.private static java.lang.String getAnnotationName(DetailAST annotation)
annotation - to get name of.private static DetailAST getNearestClassOrEnumDefinition(DetailAST ast)
ast - the start node for searching.private static boolean canBeSubclassed(DetailAST classDef)
classDef - class definition token.private static boolean hasDefaultOrExplicitNonPrivateCtor(DetailAST classDef)
classDef - class ast token.Copyright © 2001-2022. All Rights Reserved.