Randgalt / record-builder

Record builder generator for Java records

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support staged builder

reda-alaoui opened this issue · comments

Something similar to https://immutables.github.io/immutable.html#staged-builder:

A staged builder is a compile-time safe way to ensure that all required attributes are set. The API, composed of stage interfaces, forces initialization of mandatory attributes in stages, one by one, guiding via code-completion and making it impossible to even call build() before all are set.

@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?

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: #161