jhipster / prettier-java

Prettier Java Plugin
http://www.jhipster.tech/prettier-java/
Apache License 2.0
1.06k stars 103 forks source link

feat: avoid breaking on certain method chains and arguments #632

Closed jtkiesel closed 4 months ago

jtkiesel commented 5 months ago

What changed with this PR:

Method chains and arguments are now broken more similarly to Prettier JavaScript. Method invocations assumed to be static (i.e. those on capitalized identifiers) are now never broken, short method chains prefer to be broken on arguments instead, and argument lists containing a single lambda with body at the end prefer not to break.

Example

Input

class Example {

  Class<?> aaaaaaaaaaaaaaaa = new Aaaaaaaaaaaaaaaa<Bbbbbbbbbbbbbbbb>[1]
    .getClass();
  Class<?> aaaaaaaaaaaaaaaa = new Aaaaaaaaaaaaaaaa[] { new Aaaaaaaaaaaaaaaa() }
    .getClass();

  void example() {
    List
      .of(
        new double[][] { 1, 2, 3, 4.1, 5.6846465 },
        new double[][] { 1, 2, 3, 4.1, 5.6846465 },
        new double[][] { 1, 2, 3, 4.1, 5.6846465 }
      )
      .toArray(double[][]::new);

    a.of(
      b,
      c,
      d,
      e -> {
        return f;
      }
    );

    Stream
      .of(1, 2)
      .map(n -> {
        // testing method
        return n * 2;
      })
      .collect(Collectors.toList());

    return Object
      .something()
      .more()
      .and()
      .that()
      .as()
      .well()
      .but()
      .not()
      .something();
  }
}

Output

class Example {

  Class<?> aaaaaaaaaaaaaaaa = new Aaaaaaaaaaaaaaaa<
    Bbbbbbbbbbbbbbbb
  >[1].getClass();
  Class<?> aaaaaaaaaaaaaaaa = new Aaaaaaaaaaaaaaaa[] {
    new Aaaaaaaaaaaaaaaa(),
  }.getClass();

  void example() {
    List.of(
      new double[][] { 1, 2, 3, 4.1, 5.6846465 },
      new double[][] { 1, 2, 3, 4.1, 5.6846465 },
      new double[][] { 1, 2, 3, 4.1, 5.6846465 }
    ).toArray(double[][]::new);

    a.of(b, c, d, e -> {
      return f;
    });

    Stream.of(1, 2)
      .map(n -> {
        // testing method
        return n * 2;
      })
      .collect(Collectors.toList());

    return Object.something()
      .more()
      .and()
      .that()
      .as()
      .well()
      .but()
      .not()
      .something();
  }
}

Relative issues or prs:

Closes #626

jtkiesel commented 4 months ago

@clementdessoude I was able to solve the formatting issues & refactored to reduce the cognitive complexity a bit. I was also able to simplify a few things in the process. Let me know if you think the primary function could use any additional refactoring.