ConstructorsDeclarationGrouping

Since Checkstyle 10.17.0

Description

Checks that all constructors are grouped together. If there is any non-constructor code separating constructors, this check identifies and logs a violation for those ungrouped constructors. The violation message will specify the line number of the last grouped constructor. Comments between constructors are allowed.

Rationale: Grouping constructors together in a class improves code readability and maintainability. It allows developers to easily understand the different ways an object can be instantiated and the tasks performed by each constructor.

Examples

To configure the check:


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

Example of correct grouping of constructors:


public class Example1 {

  int x;

  Example1() {}

  Example1(String s) {}

  // comments between constructors are allowed.
  Example1(int x) {}

  Example1(String s, int x) {}

  void foo() {}

  private enum ExampleEnum {

    ONE, TWO, THREE;

    ExampleEnum() {}

    ExampleEnum(int x) {}

    ExampleEnum(String s) {}

    int x = 10;

    void foo() {}
  }
}

Example of incorrect grouping of constructors:


public class Example2 {

  int x;

  Example2() {}

  Example2(String s){}

  void foo() {}

  // violation 2 lines below """Constructors should be grouped together. The last
  //  grouped constructor is declared at line '18'."""
  Example2(int x) {}

  // violation 2 lines below """Constructors should be grouped together. The last
  //  grouped constructor is declared at line '18'."""
  Example2(String s, int x) {}

  private enum ExampleEnum {

    ONE, TWO, THREE;

    ExampleEnum() {}

    ExampleEnum(int x) {}

    final int x = 10;

    // violation 2 lines below """Constructors should be grouped together.
    //  The last grouped constructor is declared at line '36'."""
    ExampleEnum(String str) {}

    void foo() {}
  }

  // violation 2 lines below """Constructors should be grouped together.
  //  The last grouped constructor is declared at line '18'."""
  Example2(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.

Fully Qualified Name

com.puppycrawl.tools.checkstyle.checks.coding.ConstructorsDeclarationGroupingCheck

Use this fully qualified class name in configuration when an exact class reference is required.

Parent Module

TreeWalker