LambdaBodyLength

Since Checkstyle 8.37

Description

Checks lambda body length.

Rationale: Similar to anonymous inner classes, if lambda body becomes very long it is hard to understand and to see the flow of the method where the lambda is defined. Therefore, long lambda body should usually be extracted to method.

Properties

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

Examples

To configure the check to accept lambda bodies with up to 10 lines:


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

Example:


class Example1 {
  Runnable r = () -> { // ok, length is 10
    System.out.println(2); // line 2 of lambda
    System.out.println(3);
    System.out.println(4);
    System.out.println(5);
    System.out.println(6);
    System.out.println(7);
    System.out.println(8);
    System.out.println(9);
  }; // line 10
  // violation below 'Lambda body length is 11 lines (max allowed is 10).'
  Runnable r2 = () -> {
    System.out.println(2); // line 2 of lambda
    System.out.println(3);
    System.out.println(4);
    System.out.println(5);
    System.out.println(6);
    System.out.println(7);
    System.out.println(8);
    System.out.println(9);
    System.out.println(10);
  }; // line 11
  // violation below 'Lambda body length is 11 lines (max allowed is 10).'
  Runnable r3 = () ->
    "someString".concat("1") // line 1 of lambda
                .concat("2")
                .concat("3")
                .concat("4")
                .concat("5")
                .concat("6")
                .concat("7")
                .concat("8")
                .concat("9")
                .concat("10")
                .concat("11"); // line 11
}

To configure the check to accept lambda bodies with max 5 lines:


<module name="Checker">
  <module name="TreeWalker">
    <module name="LambdaBodyLength">
      <property name="max" value="5"/>
    </module>
  </module>
</module>

Example:


class Example2 {
  Runnable r = () -> { // ok, length is 5
    System.out.println(2);
    System.out.println(3);
    System.out.println(4);
  };
  // violation below 'Lambda body length is 6 lines (max allowed is 5).'
  Runnable r2 = () -> {
    System.out.println(2); // line 2 of lambda
    System.out.println(3);
    System.out.println(4);
    System.out.println(5);
  };
  // violation below 'Lambda body length is 6 lines (max allowed is 5).'
  Runnable r3 = () ->
    "someString".concat("1")
                .concat("2")
                .concat("3")
                .concat("4")
                .concat("5")
                .concat("6");
}

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