rewrite-static-analysis icon indicating copy to clipboard operation
rewrite-static-analysis copied to clipboard

Make setters return `this` to allow for fluent interfaces

Open greg-at-moderne opened this issue 5 months ago • 1 comments

What problem are you trying to solve?

Nicer APIs.

Describe the situation before applying the recipe

public class Person {
    private int age;

    public void setAge(int age) {
        this.age = age;
    }
}

Describe the situation after applying the recipe

public class Person {
    private int age;

    public Person setAge(int age) {
       this.age = age;
       return this; // <--------------
    }
}

Any additional context

  • One could consider doing the same to other methods returning void, not only the setters.
  • I haven't thought it through though, maybe some heuristics is needed to pick which methods it would be relevant for.

greg-at-moderne avatar Jul 07 '25 13:07 greg-at-moderne

  • Proposed implementation in https://github.com/openrewrite/rewrite-static-analysis/pull/646

e5LA avatar Jul 21 '25 19:07 e5LA