record-builder icon indicating copy to clipboard operation
record-builder copied to clipboard

Add support for a builder with required components

Open fredyw opened this issue 1 year ago • 4 comments

When the record components are annotated with @RecordBuilder.Required, the builder method will take the required record components as its parameters. This is particularly useful to ensure that the builder is always populated with the required fields at compile-time instead of relying on a runtime validation.

Example:

public record MyRecord(@Required int a, @Required int b, int c)

@Generated("io.soabase.recordbuilder.core.RecordBuilder")
public class MyRecordBuilder {
    ...
    @Generated("io.soabase.recordbuilder.core.RecordBuilder")
    public static MyRecordBuilder builder(int a, int b) {
        return new MyRecordBuilder().a(a).b(b);
    }
    ...
}

fredyw avatar Apr 09 '25 05:04 fredyw

If the arguments/parameters are required, we should not include the no-arg builder(). Or, there should be some kind of validation elsewhere.

tbh - I'm not sure I'm in favor of this. Anyone else?

Randgalt avatar Apr 21 '25 08:04 Randgalt

If the arguments/parameters are required, we should not include the no-arg builder(). Or, there should be some kind of validation elsewhere.

tbh - I'm not sure I'm in favor of this. Anyone else?

I agree that the no-arg builder() should not be included or else it defeats the purpose of this change. I updated the PR to remove it when @Required is present. Let me know what you think.

fredyw avatar Apr 21 '25 16:04 fredyw

This will get very complex quickly. RecordBuilder has so many combinations of options, etc. For example, try this:

@RecordBuilderFull
public record RequiredComponents2(@NotNull @RecordBuilder.Required String b) {
}

The builder() method should add @NotNull to the b parameter. i.e. all the parameters should be annotated like their individual setters. So, every combination of options in RecordBuilder.Options needs to be validated.

Randgalt avatar Apr 24 '25 05:04 Randgalt

This is where staged builders shine for me. Gives compile safety of must specify parameters without turning your builder constructor into a copy of the actual object constructor.

CfFanDuel avatar Apr 29 '25 12:04 CfFanDuel