Closed reda-alaoui closed 8 months ago
@reda-alaoui do I understand correctly that this generates a small builder interface for each record component with the return value another small builder interface for the next component until all components have been set then a final build method?
Yes
It sounds nice but, tbh, I simply don't have the time. A PR would be welcome and I can help if needed.
This builder is often called "fluent builder". For most typical (for records) case when all components are required, the code which needs to be generated is simple (simpler than for regular builder) and mostly consists of interface declarations.
First version, with traditional build()
as the final stage:
public interface NameAndAgeBuilder {
static NameAndAgeBuilder builder() {
return name -> age -> () -> new NameAndAge(name, age);
}
Stage1 name(String name);
interface Stage1 {
Stage2 age(int age);
}
interface Stage2 {
NameAndAge build();
}
}
The second version, without build()
is even simpler:
public interface NameAndAgeBuilder {
static NameAndAgeBuilder builder() {
return name -> age -> new NameAndAge(name, age);
}
Stage1 name(String name);
interface Stage1 {
NameAndAge age(int age);
}
}
Among other advantages, this technique enforces particular order of initialization, making code management much more convenient. For example, comparing changes in PR.
I decided to give it a whirl. Please review: https://github.com/Randgalt/record-builder/pull/161
Something similar to https://immutables.github.io/immutable.html#staged-builder: