Skip to content

Sort member variables, constructors, and methods #595

Open
@rickie

Description

@rickie

Problem

We want to sort the order of the members in a class.
Internally we are quite strict with our ordering for the sake of consistency.

The following order should be enforced in a class:

  • static member variables
  • non-static member variables
  • constructors
  • methods

Description of the proposed new feature

  • Support a stylistic preference.
  • Avoid a common gotcha, or potential problem.
  • Improve performance.

Create an Error Prone check that changes the order of the members of a class without altering the empty lines between the members of the class.

I would like to rewrite the following code:

class A {
  char a = 'a';
  private static String FOO = "foo";
  static int ONE = 1;

  void m2() {}

  public A () {}

  private static String BAR = "bar";
  char b = 'b';

  void m1() {}
  static int TWO = 2;
}

to:

class A {
  private final static String FOO = "foo";
  static int ONE = 1;
  private final static String BAR = "bar";

  static int TWO = 2;

  char a = 'a';

  char b = 'b';
  public A () {}

  void m1() {}
  void m2() {}
}

Considerations

  • For this check we don't want to sort based on the modifiers, this will be done later or in a separate Error Prone check.
  • We don't want to change anything w.r.t. the empty lines, so we want to replace only on the lines where we already had a member variable defined. For that reason the example has a few variables below a method, usually we only have these declarations at the top of the class. Put another way: ideally only SuggestedFix#replace(Tree tree, String replaceWith) is used. Canonicalization of whitespace will be handles by a separate check.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions