The main point here is that we can generate a private constructor with builder as the only argument, instead of one with all fields as arguments. It looks simpler when there're dozens of fields in the class.
Before:
@Builder
public class Example {
private String name;
private int age;
}
After:
public class Example {
private String name;
private int age;
private Example(Builder builder) {
this.name = builder.name;
this.age = builder.age;
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private String name;
private int age;
private Builder() {
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder age(int age) {
this.age = age;
return this;
}
public Example build() {
return new Example(this);
}
}
}
For the new experimental @SuperBuilder, it is already done that way.
A problem with changing the behavior of @Builder is that existing code may rely on the constructor. So this would be a breaking change.
@janrieke Glad to know that the new annotation @SuperBuilder has done it this way. I hope I can use it in my project soon. :)
Certainly my suggested change will lead to the situation that the constructor created by @Builder would have a different signature, which might break some eixsting code. However, I think it will only cost a little effort for the code maintainer to adjust their code for this breaking change. Also it will make the @Builder annotaion behaves more similarly with the @SuperBuilder one. So I think the benefit outweighs the cost.
Most helpful comment
For the new experimental
@SuperBuilder, it is already done that way.A problem with changing the behavior of
@Builderis that existing code may rely on the constructor. So this would be a breaking change.