DesignForExtension

Description

The Check finds classes that are designed for extension (subclass creation).

Nothing wrong could be with founded classes this Check make sence only for library project (not a application projects) who care about ideal OOP design to make sure class work in all cases even misusage. Even in library projects this Check most likely finds classes that are not required to check. User need to use suppressions extensively to got a benefit from this Check and avoid false positives.

ATTENTION: Only user can deside whether class is designed for extension or not. Check just show all possible. If smth inappropriate is found please use supporession.

Problem is described at "Effective Java, 2nd Edition by Josh 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 exact rule is that non-private, non-static methods of classes that can be subclassed must

  • be abstract or
  • be final or
  • have an 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();
}
        

Examples

To configure the check:

<module name="DesignForExtension"/>
        

Example of Usage

Error Messages

All messages can be customized if the default message doesn't suite you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker

FinalClass

Description

Checks that a class which has only private constructors is declared as final. Doesn't check for classes nested in interfaces or annotations, as they are always final there.

Examples

To configure the check:

<module name="FinalClass"/>
        

Example of Usage

Error Messages

All messages can be customized if the default message doesn't suite you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker

HideUtilityClassConstructor

Description

Makes sure that utility classes (classes that contain only static methods or fields in their API) do not have a public constructor.

Rationale: Instantiating utility classes does not make sense. Hence the constructors should either be private or (if you want to allow subclassing) protected. A common mistake is forgetting to hide the default constructor.

If you make the constructor protected you may want to consider the following constructor implementation technique to disallow instantiating subclasses:

public class StringUtils // not final to allow subclassing
{
    protected StringUtils() {
        // prevents calls from subclass
        throw new UnsupportedOperationException();
    }

    public static int count(char c, String s) {
        // ...
    }
}
        

Examples

To configure the check:

<module name="HideUtilityClassConstructor"/>
        

Example of Usage

Error Messages

All messages can be customized if the default message doesn't suite you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker

InnerTypeLast

Description

Check nested (inner) classes/interfaces are declared at the bottom of the class after all method and field declarations.

Examples

To configure the check:

<module name="InnerTypeLast"/>
        

Example of Usage

Error Messages

All messages can be customized if the default message doesn't suite you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker

InterfaceIsType

Description

Implements Joshua Bloch, Effective Java, Item 17 - Use Interfaces only to define types.

According to Bloch, an interface should describe a type. It is therefore inappropriate to define an interface that does not contain any methods but only constants. The Standard class javax.swing.SwingConstants is an example of a class that would be flagged by this check.

The check can be configured to also disallow marker interfaces like java.io.Serializable, that do not contain methods or constants at all.

Properties

name description type default value
allowMarkerInterfaces Controls whether marker interfaces like Serializable are allowed. Boolean true

Examples

To configure the check:

<module name="InterfaceIsType"/>
        

Example of Usage

Error Messages

All messages can be customized if the default message doesn't suite you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker

MutableException

Description

Ensures that exception classes (classes with names conforming to some regular expression and explicitly extending classes with names conforming to other regular expression) are immutable, that is, that they have only final fields.

The current algorithm is very simple: it checks that all members of exception are final. The user can still mutate an exception's instance (e.g. Throwable has a method called setStackTrace which changes the exception's stack trace). But, at least, all information provided by this exception type is unchangeable.

Rationale: Exception instances should represent an error condition. Having non final fields not only allows the state to be modified by accident and therefore mask the original condition but also allows developers to accidentally forget to set the initial state. In both cases, code catching the exception could draw incorrect conclusions based on the state.

Properties

name description type default value
format pattern for exception class names regular expression ^.*Exception$|^.*Error$|^.*Throwable$
extendedClassNameFormat pattern for extended class names regular expression ^.*Exception$|^.*Error$|^.*Throwable$

Examples

To configure the check:

<module name="MutableException"/>
        

Example of Usage

Error Messages

All messages can be customized if the default message doesn't suite you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker

OneTopLevelClass

Description

Checks that each top-level class, interface or enum resides in a source file of its own. Official description of a 'top-level' term:7.6. Top Level Type Declarations. If file doesn't contains public class, enum or interface, top-level type is the first type in file.

Examples

An example of check's configuration:

<module name="OneTopLevelClass"/>
        

ATTENTION: This Check does not support customization of validated tokens, so do not use the "tokens" property.

An example of code with violations:

public class Foo{
    //methods
}

class Foo2{
    //methods
}
        

An example of code without public top-level type:

class Foo{ // top-level class
    //methods
}

class Foo2{
    //methods
}
        

An example of code without violations:

public class Foo{
    //methods
}
        

Error Messages

All messages can be customized if the default message doesn't suite you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker

ThrowsCount

Description

Restricts throws statements to a specified count (4 by default). Methods with "Override" or "java.lang.Override" annotation are skipped from validation as current class cannot change signature of these methods.

Rationale: Exceptions form part of a method's interface. Declaring a method to throw too many differently rooted exceptions makes exception handling onerous and leads to poor programming practices such as writing code like catch(Exception ex). 4 is the empirical value which is based on reports that we had for the ThrowsCountCheck over big projects such as OpenJDK. This check also forces developers to put exceptions into a hierarchy such that in the simplest case, only one type of exception need be checked for by a caller but any subclasses can be caught specifically if necessary.For more information on rules for the exceptions and their issues, see Effective Java: Programming Language Guide Second Edition by Joshua Bloch pages 264-273.

ignorePrivateMethods - allows to skip private methods as they do not cause problems for other classes.

Properties

name description type default value
max maximum allowed number of throws statements Integer 4
ignorePrivateMethods whether private methods must be ignored Boolean true

Examples

To configure the check so that it doesn't allow more than two throws per method:

<module name="ThrowsCount">
    <property name="max" value="2"/>
</module>
        

To configure the check so that it doesn't skip private methods:

<module name="ThrowsCount">
    <property name="ignorePrivateMethods" value="false"/>
</module>
        

Example of Usage

Error Messages

All messages can be customized if the default message doesn't suite you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker

VisibilityModifier

Description

Checks visibility of class members. Only static final, immutable or annotated by specified annotation members may be public; other class members must be private unless the property protectedAllowed or packageAllowed is set.

Public members are not flagged if the name matches the public member regular expression (contains "^serialVersionUID$" by default).

Note that Checkstyle 2 used to include "^f[A-Z][a-zA-Z0-9]*$" in the default pattern to allow names used in container-managed persistence for Enterprise JavaBeans (EJB) 1.1 with the default settings. With EJB 2.0 it is no longer necessary to have public access for persistent fields, so the default has been changed.

Rationale: Enforce encapsulation.

Check also has options making it less strict:

ignoreAnnotationCanonicalNames - the list of annotations which ignore variables in consideration. If user will provide short annotation name that type will match to any named the same type without consideration of package

allowPublicImmutableFields - which allows immutable fields be declared as public if defined in final class. Default value is true

Field is known to be immutable if: - It's declared as final - Has either a primitive type or instance of class user defined to be immutable (such as String, ImmutableCollection from Guava and etc)

Classes known to be immutable are listed in immutableClassCanonicalNames by their canonical names.

Rationale: Forcing all fields of class to have private modified by default is good in most cases, but in some cases it drawbacks in too much boilerplate get/set code. One of such cases are immutable classes.

Restriction: Check doesn't check if class is immutable, there's no checking if accessory methods are missing and all fields are immutable, we only check if current field is immutable and defined in final class

Star imports are out of scope of this Check. So if one of type imported via star import collides with user specified one by its short name - there won't be Check's violation.

Properties

name description type default value
packageAllowed whether package visible members are allowed boolean false
protectedAllowed whether protected members are allowed boolean false
publicMemberPattern pattern for public members that should be ignored regular expression ^serialVersionUID$
allowPublicImmutableFields allows immutable fields be declared as public if defined in final class boolean true
immutableClassCanonicalNames immutable classes canonical names String Set java.lang.String, java.lang.Integer, java.lang.Byte, java.lang.Character, java.lang.Short, java.lang.Boolean, java.lang.Long, java.lang.Double, java.lang.Float, java.lang.StackTraceElement, java.math.BigInteger, java.math.BigDecimal, java.io.File, java.util.Locale, java.util.UUID, java.net.URL, java.net.URI, java.net.Inet4Address, java.net.Inet6Address, java.net.InetSocketAddress,
ignoreAnnotationCanonicalNames ignore annotations canonical names String Set org.junit.Rule, org.junit.ClassRule, com.google.common.annotations.VisibleForTesting

Examples

To configure the check:

<module name="VisibilityModifier"/>
        

To configure the check so that it allows package visible members:

<module name="VisibilityModifier">
    <property name="packageAllowed" value="true"/>
</module>
        

To configure the check so that it allows no public members:

<module name="VisibilityModifier">
    <property name="publicMemberPattern" value="^$"/>
</module>
        

To configure the Check so that it allows public immutable fields (mostly for immutable classes):

<module name="VisibilityModifier"/>
        

Example of allowed public immutable fields:

public class ImmutableClass
{
    public final ImmutableSet<String> includes; // No warning
    public final ImmutableSet<String> excludes; // No warning
    public final java.lang.String notes; // No warning
    public final BigDecimal value; // No warning

    public ImmutableClass(Collection<String> includes, Collection<String> excludes,
                 BigDecimal value, String notes)
    {
        this.includes = ImmutableSet.copyOf(includes);
        this.excludes = ImmutableSet.copyOf(excludes);
        this.value = value;
        this.notes = notes;
    }
}
        

To configure the Check which allows user specified immutable class names:

<module name="VisibilityModifier">
    <property name="immutableClassCanonicalNames" value="
    com.google.common.collect.ImmutableSet"/>
</module>
        

Example of allowed public immutable fields:

public class ImmutableClass
{
    public final ImmutableSet<String> includes; // No warning
    public final ImmutableSet<String> excludes; // No warning
    public final java.lang.String notes; // Warning here because
                                         //'java.lang.String' wasn't specified as allowed class
    public final int someValue; // No warning

    public ImmutableClass(Collection<String> includes, Collection<String> excludes,
                 String notes, int someValue)
    {
        this.includes = ImmutableSet.copyOf(includes);
        this.excludes = ImmutableSet.copyOf(excludes);
        this.value = value;
        this.notes = notes;
        this.someValue = someValue;
    }
}
        

To configure the Check passing fields annotated with @com.annotation.CustomAnnotation:

<module name="VisibilityModifier">
  <property name="ignoreAnnotationCanonicalNames" value=
  "com.annotation.CustomAnnotation"/>
</module>
        

Example of allowed field:

class SomeClass
{
    @com.annotation.CustomAnnotation
    String annotatedString; // no warning
    @CustomAnnotation
    String shortCustomAnnotated; // no warning
}
        

To configure the Check passing fields annotated with @org.junit.Rule, @org.junit.ClassRule and @com.google.common.annotations.VisibleForTesting annotations:

<module name="VisibilityModifier"/>
        

Example of allowed fields:

class SomeClass
{
    @org.junit.Rule
    public TemporaryFolder publicJUnitRule = new TemporaryFolder(); // no warning
    @org.junit.ClassRule
    public static TemporaryFolder publicJUnitClassRule = new TemporaryFolder(); // no warning
    @com.google.common.annotations.VisibleForTesting
    public String testString = ""; // no warning
}
        

To configure the Check passing fields annotated with short annotation name:

<module name="VisibilityModifier">
  <property name="ignoreAnnotationCanonicalNames"
  value="CustomAnnotation"/>
</module>
        

Example of allowed fields:

class SomeClass
{
    @CustomAnnotation
    String customAnnotated; // no warning
    @com.annotation.CustomAnnotation
    String customAnnotated1; // no warning
    @mypackage.annotation.CustomAnnotation
    String customAnnotatedAnotherPackage; // another package but short name matches
                                          // so no violation
}
        

Example of Usage

Error Messages

All messages can be customized if the default message doesn't suite you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker