AnonInnerLength

Since Checkstyle 3.2

Description

Checks for long anonymous inner classes.

Rationale: If an anonymous inner class becomes very long it is hard to understand and to see the flow of the method where the class is defined. Therefore, long anonymous inner classes should usually be refactored into a named inner class. See also Bloch, Effective Java, p. 93.

Properties

name description type default value since
max Specify the maximum number of lines allowed. int 20 3.2

Examples

To configure the check to accept anonymous classes with up to 20 lines by default:

<module name="Checker">
  <module name="TreeWalker">
    <module name="AnonInnerLength"/>
  </module>
</module>
        

Example1:

class Example1 {
  void testMethod() {
    Runnable shortAnonClass = new Runnable() {
      @Override
      public void run() {
        System.out.println("Short anonymous class.");
      }
    };
    shortAnonClass.run();

    Runnable longAnonClass = new Runnable() {
      @Override
      public void run() {
        System.out.println("This is a lengthy anonymous class.");
        System.out.println("It has too many lines of code.");
        System.out.println("Exceeding the length limit.");
        System.out.println("This would trigger the AnonInnerLength rule.");
      }
    };
    longAnonClass.run();
  }
}
        

To configure the check to accept anonymous classes with up to 7 lines:

<module name="Checker">
  <module name="TreeWalker">
    <module name="AnonInnerLength">
      <property name="max" value="7"/>
    </module>
  </module>
</module>
        

Example2:

class Example2 {
  void testMethod() {
    Runnable shortAnonClass = new Runnable() {
      @Override
      public void run() {
        System.out.println("Short anonymous class.");
      }
    };
    shortAnonClass.run();
    // violation below, 'Anonymous inner class length is 9 lines (max allowed is 7)'
    Runnable longAnonClass = new Runnable() {
      @Override
      public void run() {
        System.out.println("This is a lengthy anonymous class.");
        System.out.println("It has too many lines of code.");
        System.out.println("Exceeding the length limit.");
        System.out.println("This would trigger the AnonInnerLength rule.");
      }
    };
    longAnonClass.run();
  }
}
        

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.sizes

Parent Module

TreeWalker