Content

DesignForExtension

Since Checkstyle 3.1

Description

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();
}
        

Properties

name description type default value since
ignoredAnnotations Specify annotations which allow the check to skip the method from validation. String[] After, AfterClass, Before, BeforeClass, Test 7.2
requiredJavadocPhrase Specify the comment text pattern which qualifies a method as designed for extension. Supports multi-line regex. Pattern ".*" 8.40

Examples

To configure the check:

<module name="DesignForExtension"/>
        

Example:

public abstract class Foo {
  private int bar;

  public int m1() {return 2;}  // Violation. No javadoc.

  public int m2() {return 8;}  // Violation. No javadoc.

  private void m3() {m4();}  // OK. Private method.

  protected void m4() { }  // OK. No implementation.

  public abstract void m5();  // OK. Abstract method.

  /**
   * This implementation ...
   @return some int value.
   */
  public int m6() {return 1;}  // OK. Have javadoc on overridable method.

  /**
   * Some comments ...
   */
  public int m7() {return 1;}  // OK. Have javadoc on overridable method.

  /**
   * This
   * implementation ...
   */
  public int m8() {return 2;}  // OK. Have javadoc on overridable method.

  @Override
  public String toString() {  // Violation. No javadoc for @Override method.
    return "";
  }
}
        

To configure the check to allow methods which have @Override annotations to be designed for extension.

<module name="DesignForExtension">
  <property name="ignoredAnnotations" value="Override"/>
</module>
        

Example:

public abstract class Foo {
  private int bar;

  public int m1() {return 2;}  // Violation. No javadoc.

  public int m2() {return 8;}  // Violation. No javadoc.

  private void m3() {m4();}  // OK. Private method.

  protected void m4() { }  // OK. No implementation.

  public abstract void m5();  // OK. Abstract method.

  /**
   * This implementation ...
   @return some int value.
   */
  public int m6() {return 1;}  // OK. Have javadoc on overridable method.

  /**
   * Some comments ...
   */
  public int m7() {return 1;}  // OK. Have javadoc on overridable method.

  /**
   * This
   * implementation ...
   */
  public int m8() {return 2;}  // OK. Have javadoc on overridable method.

  @Override
  public String toString() {  // OK. Have javadoc on overridable method.
    return "";
  }
}
        

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>
        

Example:

public abstract class Foo {
  private int bar;

  public int m1() {return 2;}  // Violation. No javadoc.

  public int m2() {return 8;}  // Violation. No javadoc.

  private void m3() {m4();}  // OK. Private method.

  protected void m4() { }  // OK. No implementation.

  public abstract void m5();  // OK. Abstract method.

  /**
   * This implementation ...
   @return some int value.
   */
  public int m6() {return 1;}  // OK. Have required javadoc.

  /**
   * Some comments ...
   */
  public int m7() {return 1;}  // Violation. No required javadoc.

  /**
   * This
   * implementation ...
   */
  public int m8() {return 2;}  // Violation. No required javadoc.

  @Override
  public String toString() {  // Violation. No required javadoc.
    return "";
  }
}
        

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>
        

Example:

public abstract class Foo {
  private int bar;

  public int m1() {return 2;}  // Violation. No javadoc.

  public int m2() {return 8;}  // Violation. No javadoc.

  private void m3() {m4();}

  protected void m4() { }  // OK. No implementation.

  public abstract void m5();  // OK. Abstract method.

  /**
   * This implementation ...
   @return some int value.
   */
  public int m6() {return 1;}  // OK. Have required javadoc.

  /**
   * Some comments ...
   */
  public int m7() {return 1;}  // Violation. No required javadoc.

  /**
   * This
   * implementation ...
   */
  public int m8() {return 2;}  // OK. Have required javadoc.

  @Override
  public String toString() {  // Violation. No required javadoc.
    return "";
  }
}
        

Example of Usage

Violation Messages

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

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker

FinalClass

Since Checkstyle 3.1

Description

Checks that a class that has only private constructors and has no descendant classes is declared as final.

Examples

To configure the check:

<module name="FinalClass"/>
        

Example:

final class MyClass { // OK
  private MyClass() { }
}

class MyClass { // violation, class should be declared final
  private MyClass() { }
}

class MyClass { // OK, since it has a public constructor
  int field1;
  String field2;
  private MyClass(int value) {
    this.field1 = value;
    this.field2 = " ";
  }
  public MyClass(String value) {
    this.field2 = value;
    this.field1 = 0;
  }
}

class TestAnonymousInnerClasses { // OK, class has an anonymous inner class.
    public static final TestAnonymousInnerClasses ONE = new TestAnonymousInnerClasses() {

    };

    private TestAnonymousInnerClasses() {
    }
}
        

Example of Usage

Violation Messages

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

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker

HideUtilityClassConstructor

Since Checkstyle 3.1

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:

class Test { // violation, class only has a static method and a constructor

  public Test() {
  }

  public static void fun() {
  }
}

class Foo { // OK

  private Foo() {
  }

  static int n;
}

class Bar { // OK

  protected Bar() {
    // prevents calls from subclass
    throw new UnsupportedOperationException();
  }
}

class UtilityClass { // violation, class only has a static field

  static float f;
}
        

Example of Usage

Violation Messages

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

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker

InnerTypeLast

Since Checkstyle 5.2

Description

Checks nested (internal) classes/interfaces are declared at the bottom of the primary (top-level) class after all init and static init blocks, method, constructor and field declarations.

Examples

To configure the check:

<module name="InnerTypeLast"/>
        

Example:

class Test {
    private String s; // OK
    class InnerTest1 {}
    public void test() {} // violation, method should be declared before inner types.
}

class Test2 {
    static {}; // OK
    class InnerTest1 {}
    public Test2() {} // violation, constructor should be declared before inner types.
}

class Test3 {
    private String s; // OK
    public void test() {} // OK
    class InnerTest1 {}
}
        

Example of Usage

Violation Messages

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

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker

InterfaceIsType

Since Checkstyle 3.1

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 interface javax.swing.SwingConstants is an example of an interface 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 since
allowMarkerInterfaces Control whether marker interfaces like Serializable are allowed. boolean true 3.1

Examples

To configure the check:

<module name="InterfaceIsType"/>
        

Example:

public interface Test1 { // violation
    int a = 3;
}

public interface Test2 { // OK

}

public interface Test3 { // OK
    int a = 3;
    void test();
}
        

To configure the check to report violation so that it doesn't allow Marker Interfaces:

<module name="InterfaceIsType">
  <property name="allowMarkerInterfaces" value="false"/>
</module>
        

Example:

public interface Test1 { // violation
    int a = 3;
}

public interface Test2 { // violation

}
        

Example of Usage

Violation Messages

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

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker

MutableException

Since Checkstyle 3.2

Description

Ensures that exception classes (classes with names conforming to some pattern and explicitly extending classes with names conforming to other pattern) 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 since
format Specify pattern for exception class names. Pattern "^.*Exception$|^.*Error$|^.*Throwable$" 3.2
extendedClassNameFormat Specify pattern for extended class names. Pattern "^.*Exception$|^.*Error$|^.*Throwable$" 6.2

Examples

To configure the check:

<module name="MutableException"/>
        

Example:

class FirstClass extends Exception {
  private int code; // OK, class name doesn't match with default pattern

  public FirstClass() {
    code = 1;
  }
}

class MyException extends Exception {
  private int code; // violation, The field 'code' must be declared final

  public MyException() {
    code = 2;
  }
}

class MyThrowable extends Throwable {
  final int code; // OK
  String message; // violation, The field 'message' must be declared final

  public MyThrowable(int code, String message) {
    this.code = code;
    this.message = message;
  }
}

class BadException extends java.lang.Exception {
  int code; // violation, The field 'code' must be declared final

  public BadException(int code) {
    this.code = code;
  }
}
          

To configure the check so that it checks for class name that ends with 'Exception':

<module name="MutableException">
  <property name="format" value="^.*Exception$"/>
</module>
        

Example:

class FirstClass extends Exception {
  private int code; // OK, class name doesn't match with given pattern

  public FirstClass() {
    code = 1;
  }
}

class MyException extends Exception {
  private int code; // violation, The field 'code' must be declared final

  public MyException() {
    code = 2;
  }
}

class MyThrowable extends Throwable {
  final int code; // OK, class name doesn't match with given pattern
  String message; // OK, class name doesn't match with given pattern

  public MyThrowable(int code, String message) {
    this.code = code;
    this.message = message;
  }
}

class BadException extends java.lang.Exception {
  int code; // violation, The field 'code' must be declared final

  public BadException(int code) {
    this.code = code;
  }
}
          

To configure the check so that it checks for type name that is used in 'extends' and ends with 'Throwable':

<module name="MutableException">
  <property name="extendedClassNameFormat" value="^.*Throwable$"/>
</module>
        

Example:

class FirstClass extends Exception {
  private int code; // OK, extended class name doesn't match with given pattern

  public FirstClass() {
    code = 1;
  }
}

class MyException extends Exception {
  private int code; // OK, extended class name doesn't match with given pattern

  public MyException() {
    code = 2;
  }
}

class MyThrowable extends Throwable {
  final int code; // OK
  String message; // violation, The field 'message' must be declared final

  public MyThrowable(int code, String message) {
    this.code = code;
    this.message = message;
  }
}

class BadException extends java.lang.Exception {
  int code; // OK, extended class name doesn't match with given pattern

  public BadException(int code) {
    this.code = code;
  }
}
          

Example of Usage

Violation Messages

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

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker

OneTopLevelClass

Since Checkstyle 5.8

Description

Checks that each top-level class, interface, enum or annotation 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 contain public class, interface, enum or annotation, top-level type is the first type in file.

Examples

To configure the check:

<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 { // OK, first top-level class
  // methods
}

class Foo2 { // violation, second top-level class
  // methods
}

record Foo3 { // violation, third top-level "class"
  // methods
}
          

An example of code without public top-level type:

class Foo { // OK, first top-level class
  // methods
}

class Foo2 { // violation, second top-level class
  // methods
}
          

An example of code without violations:

public class Foo { // OK, only one top-level class
  // methods
}
          

Example of Usage

Violation Messages

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

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker

ThrowsCount

Since Checkstyle 3.2

Description

Restricts throws statements to a specified count. 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 since
max Specify maximum allowed number of throws statements. int 4 3.2
ignorePrivateMethods Allow private methods to be ignored. boolean true 6.7

Examples

To configure check:

<module name="ThrowsCount"/>
        

Example:

class Test {
    public void myFunction() throws CloneNotSupportedException,
                                ArrayIndexOutOfBoundsException,
                                StringIndexOutOfBoundsException,
                                IllegalStateException,
                                NullPointerException { // violation, max allowed is 4
        // body
    }

    public void myFunc() throws ArithmeticException,
                                NumberFormatException { // ok
        // body
    }

    private void privateFunc() throws CloneNotSupportedException,
                                ClassNotFoundException,
                                IllegalAccessException,
                                ArithmeticException,
                                ClassCastException { // ok, private methods are ignored
        // body
    }

}
        

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>
        

Example:

class Test {
    public void myFunction() throws IllegalStateException,
                                ArrayIndexOutOfBoundsException,
                                NullPointerException { // violation, max allowed is 2
        // body
    }

    public void myFunc() throws ArithmeticException,
                                NumberFormatException { // ok
        // body
    }

    private void privateFunc() throws CloneNotSupportedException,
                                ClassNotFoundException,
                                IllegalAccessException,
                                ArithmeticException,
                                ClassCastException { // ok, private methods are ignored
        // body
    }

}
        

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

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

Example:

class Test {
    public void myFunction() throws CloneNotSupportedException,
                                ArrayIndexOutOfBoundsException,
                                StringIndexOutOfBoundsException,
                                IllegalStateException,
                                NullPointerException { // violation, max allowed is 4
        // body
    }

    public void myFunc() throws ArithmeticException,
                                NumberFormatException { // ok
        // body
    }

    private void privateFunc() throws CloneNotSupportedException,
                                ClassNotFoundException,
                                IllegalAccessException,
                                ArithmeticException,
                                ClassCastException { // violation, max allowed is 4
        // body
    }

    private void func() throws IllegalStateException,
                                NullPointerException { // ok
        // body
    }

}
        

Example of Usage

Violation Messages

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

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker

VisibilityModifier

Since Checkstyle 3.0

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 want to provide short annotation name that type will match to any named the same type without consideration of package.

allowPublicFinalFields - which allows public final fields.

allowPublicImmutableFields - which allows immutable fields to be declared as public if defined in final class.

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, etc.)

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

Property Rationale: Forcing all fields of class to have private modifier 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 or final. Under the flag allowPublicImmutableFields, the enclosing class must also be final, to encourage immutability. Under the flag allowPublicFinalFields, the final modifier on the enclosing class is optional.

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 since
packageAllowed Control whether package visible members are allowed. boolean false 3.0
protectedAllowed Control whether protected members are allowed. boolean false 3.0
publicMemberPattern Specify pattern for public members that should be ignored. Pattern "^serialVersionUID$" 3.0
allowPublicFinalFields Allow final fields to be declared as public. boolean false 7.0
allowPublicImmutableFields Allow immutable fields to be declared as public if defined in final class. boolean false 6.4
immutableClassCanonicalNames Specify immutable classes canonical names. String[] java.io.File, java.lang.Boolean, java.lang.Byte, java.lang.Character, java.lang.Double, java.lang.Float, java.lang.Integer, java.lang.Long, java.lang.Short, java.lang.StackTraceElement, java.lang.String, java.math.BigDecimal, java.math.BigInteger, java.net.Inet4Address, java.net.Inet6Address, java.net.InetSocketAddress, java.net.URI, java.net.URL, java.util.Locale, java.util.UUID 6.4.1
ignoreAnnotationCanonicalNames Specify annotations canonical names which ignore variables in consideration. String[] com.google.common.annotations.VisibleForTesting, org.junit.ClassRule, org.junit.Rule 6.5

Examples

To configure the check:

<module name="VisibilityModifier"/>
        

Example with default values:

public class MyClass {
 private int myPrivateField1;

 int field1;              // violation, must have a visibility modifier

 protected String field2; // violation, protected visibility is not allowed

 public int field3 = 42;  // violation, not static final, immutable,
                          // nor matching the pattern

 public long serialVersionUID = 1L;

 public static final int field4 = 42;

 public final int field5 = 42;          // violation, public immutable fields are not allowed
 public final java.lang.String notes;   // violation, public immutable fields are not allowed

 public final Set<String> mySet1 = new HashSet<>();  // violation, HashSet is mutable

 public final ImmutableSet<String> mySet2;           // violation,
                                                     // immutable type not in config

 public final ImmutableMap<String, Object> objects1; // violation,
                                                     // immutable type not in config

 @com.annotation.CustomAnnotation
 String annotatedString;      // violation, annotation is not configured

 @CustomAnnotation
 String shortCustomAnnotated; // violation, annotation is not configured

 @com.google.common.annotations.VisibleForTesting
 public String testString = "";
}
        

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

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

Example of allowed package visible members:

public class MyClass {
 private int myPrivateField1;

 int field1;

 protected String field2; // violation, protected visibility is not allowed

 public int field3 = 42;  // violation, not static final, immutable,
                          // nor matching the pattern

 public long serialVersionUID = 1L;

 public static final int field4 = 42;

 public final int field5 = 42;          // violation, public immutable fields are not allowed
 public final java.lang.String notes;   // violation, public immutable fields are not allowed

 public final Set<String> mySet1 = new HashSet<>();  // violation, HashSet is mutable

 public final ImmutableSet<String> mySet2;           // violation,
                                                     // immutable type not in config

 public final ImmutableMap<String, Object> objects1; // violation,
                                                     // immutable type not in config

 @com.annotation.CustomAnnotation
 String annotatedString;

 @CustomAnnotation
 String shortCustomAnnotated;

 @com.google.common.annotations.VisibleForTesting
 public String testString = "";
}
        

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

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

Example of allowed protected visible members:

public class MyClass {
 private int myPrivateField1;

 int field1;              // violation, must have a visibility modifier

 protected String field2;

 public int field3 = 42;  // violation, not static final, immutable,
                          // nor matching the pattern

 public long serialVersionUID = 1L;

 public static final int field4 = 42;

 public final int field5 = 42;          // violation, public immutable fields are not allowed
 public final java.lang.String notes;   // violation, public immutable fields are not allowed

 public final Set<String> mySet1 = new HashSet<>();  // violation, HashSet is mutable

 public final ImmutableSet<String> mySet2;           // violation,
                                                     // immutable type not in config

 public final ImmutableMap<String, Object> objects1; // violation,
                                                     // immutable type not in config

 @com.annotation.CustomAnnotation
 String annotatedString;      // violation, annotation is not configured

 @CustomAnnotation
 String shortCustomAnnotated; // violation, annotation is not configured

 @com.google.common.annotations.VisibleForTesting
 public String testString = "";
}
        

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

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

Example of not allowed public members:

public class MyClass {
 private int myPrivateField1;

 int field1;              // violation, must have a visibility modifier

 protected String field2; // violation, protected visibility is not allowed

 public int field3 = 42;  // violation, not static final, immutable,
                          // nor matching the pattern

 public long serialVersionUID = 1L;  // Violation, not matched the pattern '^$'

 public static final int field4 = 42;

 public final int field5 = 42;          // violation, public immutable fields are not allowed
 public final java.lang.String notes;   // violation, public immutable fields are not allowed

 public final Set<String> mySet1 = new HashSet<>();  // violation, HashSet is mutable

 public final ImmutableSet<String> mySet2;           // violation,
                                                     // immutable type not in config

 public final ImmutableMap<String, Object> objects1; // violation,
                                                     // immutable type not in config

 @com.annotation.CustomAnnotation
 String annotatedString;      // violation, annotation is not configured

 @CustomAnnotation
 String shortCustomAnnotated; // violation, annotation is not configured

 @com.google.common.annotations.VisibleForTesting
 public String testString = "";
}
        

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

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

Example of allowed public immutable fields:

public final class MyClass {
 private int myPrivateField1;

 int field1;              // violation, must have a visibility modifier

 protected String field2; // violation, protected visibility is not allowed

 public int field3 = 42;  // violation, not static final, immutable,
                          // nor matching the pattern

 public long serialVersionUID = 1L;

 public static final int field4 = 42;

 public final int field5 = 42;
 public final java.lang.String notes;

 public final Set<String> mySet1 = new HashSet<>();  // violation, HashSet is mutable

 public final ImmutableSet<String> mySet2;           // violation,
                                                     // immutable type not in config

 public final ImmutableMap<String, Object> objects1; // violation,
                                                     // immutable type not in config

 @com.annotation.CustomAnnotation
 String annotatedString;      // violation, annotation is not configured

 @CustomAnnotation
 String shortCustomAnnotated; // violation, annotation is not configured

 @com.google.common.annotations.VisibleForTesting
 public String testString = "";
}
        

To configure the Check in order to allow user specified immutable class names:

<module name="VisibilityModifier">
  <property name="allowPublicImmutableFields" value="true"/>
  <property name="immutableClassCanonicalNames"
    value="com.google.common.collect.ImmutableSet, java.lang.String"/>
</module>
        

Example of allowed public immutable fields:

public final class MyClass {
 private int myPrivateField1;

 int field1;              // violation, must have a visibility modifier

 protected String field2; // violation, protected visibility is not allowed

 public int field3 = 42;  // violation, not static final, immutable,
                          // nor matching the pattern

 public long serialVersionUID = 1L;

 public static final int field4 = 42;

 public final int field5 = 42;
 public final java.lang.String notes;

 public final Set<String> mySet1 = new HashSet<>();  // violation, HashSet is mutable

 public final ImmutableSet<String> mySet2;

 public final ImmutableMap<String, Object> objects1; // violation
                                                     // immutable type not in config

 @com.annotation.CustomAnnotation
 String annotatedString;      // violation, annotation is not configured

 @CustomAnnotation
 String shortCustomAnnotated; // violation, annotation is not configured

 @com.google.common.annotations.VisibleForTesting
 public String testString = "";
}
        

Note, if allowPublicImmutableFields is set to true, the check will also check whether generic type parameters are immutable. If at least one generic type parameter is mutable, there will be a violation.

<module name="VisibilityModifier">
  <property name="allowPublicImmutableFields" value="true"/>
  <property name="immutableClassCanonicalNames"
    value="com.google.common.collect.ImmutableSet,
           com.google.common.collect.ImmutableMap,
           java.lang.String"/>
</module>
        

Example of how the check works:

public final class MyClass {
 private int myPrivateField1;

 int field1;              // violation, must have a visibility modifier

 protected String field2; // violation, protected visibility is not allowed

 public int field3 = 42;  // violation, not static final, immutable,
                          // nor matching the pattern

 public long serialVersionUID = 1L;

 public static final int field4 = 42;

 public final int field5 = 42;
 public final java.lang.String notes;

 public final Set<String> mySet1 = new HashSet<>();  // violation, HashSet is mutable

 public final ImmutableSet<String> mySet2;

 public final ImmutableMap<String, Object> objects1; // violation
                                                     // 'Object' still considered as mutable

 @com.annotation.CustomAnnotation
 String annotatedString;      // violation, annotation is not configured

 @CustomAnnotation
 String shortCustomAnnotated; // violation, annotation is not configured

 @com.google.common.annotations.VisibleForTesting
 public String testString = "";
}
        

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:

public final class MyClass {
 private int myPrivateField1;

 int field1;              // violation, must have a visibility modifier

 protected String field2; // violation, protected visibility is not allowed

 public int field3 = 42;  // violation, not static final, immutable,
                          // nor matching the pattern

 public long serialVersionUID = 1L;

 public static final int field4 = 42;

 public final int field5 = 42;          // violation, public immutable fields are not allowed
 public final java.lang.String notes;   // violation, public immutable fields are not allowed

 public final Set<String> mySet1 = new HashSet<>();  // violation, HashSet is mutable

 public final ImmutableSet<String> mySet2;           // violation,
                                                     // immutable type not in config

 public final ImmutableMap<String, Object> objects1; // violation,
                                                     // immutable type not in config

 @com.annotation.CustomAnnotation
 String annotatedString;

 @CustomAnnotation
 String shortCustomAnnotated;

 @com.google.common.annotations.VisibleForTesting
 public String testString = ""; // violation, annotation is not configured
}
        

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:

public final class MyClass {
 private int myPrivateField1;

 int field1;              // violation, must have a visibility modifier

 protected String field2; // violation, protected visibility is not allowed

 public int field3 = 42;  // violation, not static final, immutable,
                          // nor matching the pattern

 public long serialVersionUID = 1L;

 public static final int field4 = 42;

 public final int field5 = 42;          // violation, public immutable fields are not allowed
 public final java.lang.String notes;   // violation, public immutable fields are not allowed

 public final Set<String> mySet1 = new HashSet<>();  // violation, HashSet is mutable

 public final ImmutableSet<String> mySet2;           // violation,
                                                     // immutable type not in config

 public final ImmutableMap<String, Object> objects1; // violation,
                                                     // immutable type not in config

 @com.annotation.CustomAnnotation
 String annotatedString;      // violation, annotation is not configured

 @CustomAnnotation
 String shortCustomAnnotated; // violation, annotation is not configured

 @com.google.common.annotations.VisibleForTesting
 public String testString = "";
}
        

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

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

Example of allowed fields:

public final class MyClass {
 private int myPrivateField1;

 int field1;              // violation, must have a visibility modifier

 protected String field2; // violation, protected visibility is not allowed

 public int field3 = 42;  // violation, not static final, immutable,
                          // nor matching the pattern

 public long serialVersionUID = 1L;

 public static final int field4 = 42;

 public final int field5 = 42;          // violation, public immutable fields are not allowed
 public final java.lang.String notes;   // violation, public immutable fields are not allowed

 public final Set<String> mySet1 = new HashSet<>();  // violation, HashSet is mutable

 public final ImmutableSet<String> mySet2;           // violation,
                                                     // immutable type not in config

 public final ImmutableMap<String, Object> objects1; // violation,
                                                     // immutable type not in config

 @com.annotation.CustomAnnotation
 String annotatedString;        // violation, annotation is not configured

 @CustomAnnotation
 String shortCustomAnnotated;

 @com.google.common.annotations.VisibleForTesting
 public String testString = ""; // violation, annotation is not configured
}
        

To understand the difference between allowPublicImmutableFields and allowPublicFinalFields options, please, study the following examples.

1) To configure the check to use only 'allowPublicImmutableFields' option:

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

Code example:

public class InputPublicImmutable {
  public final int someIntValue; // violation
  public final ImmutableSet<String> includes; // violation
  public final java.lang.String notes; // violation
  public final BigDecimal value; // violation
  public final List list; // violation

  public InputPublicImmutable(Collection<String> includes,
        BigDecimal value, String notes, int someValue, List l) {
    this.includes = ImmutableSet.copyOf(includes);
    this.value = value;
    this.notes = notes;
    this.someIntValue = someValue;
    this.list = l;
  }
}
        

2) To configure the check to use only 'allowPublicFinalFields' option:

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

Code example:

public class InputPublicImmutable {
  public final int someIntValue; // ok
  public final ImmutableSet<String> includes; // ok
  public final java.lang.String notes; // ok
  public final BigDecimal value; // ok
  public final List list; // ok

  public InputPublicImmutable(Collection<String> includes,
        BigDecimal value, String notes, int someValue, List l) {
    this.includes = ImmutableSet.copyOf(includes);
    this.value = value;
    this.notes = notes;
    this.someIntValue = someValue;
    this.list = l;
  }
}
        

Example of Usage

Violation Messages

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

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker