helospark / SparkBuilderGenerator

Eclipse plugin to generate builders
MIT License
38 stars 12 forks source link

Avoid creating extra constructor on builders for records #71

Closed mdewilde closed 3 weeks ago

mdewilde commented 2 months ago

You added the ability to create builders for records (issue 69) after I requested it last year. Thanks for that, I use it often.

I'd like to request a tweak to the logic.

When generating a builder for a record, the plugin should not create a private constructor in the record that takes a Builder instance.

That is because a record by its very nature always has a public full-argument constructor which can be called from the Builder.

As an example, this is what the plugin currently does:

public record Request(Object argument) {

    private Request(Builder builder) {
        this(builder.argument);
    }

    public static Builder builder() {
        return new Builder();
    }

    public static final class Builder {
        private Object argument;

        private Builder() {}

        public Builder argument(Object argument) {
            this.argument = argument;
            return this;
        }

        public Request build() {
            return new Request(this);
        }
    }

}

This is what I believe would be a better alternative:

public record Request(Object argument) {

    public static Builder builder() {
        return new Builder();
    }

    public static final class Builder {
        private Object argument;

        private Builder() {}

        public Builder argument(Object argument) {
            this.argument = argument;
            return this;
        }

        public Request build() {
            return new Request(argument);
        }
    }

}

Less code and a more strict single canonical constructor for record instances.

helospark commented 2 months ago

Hi @mdewilde ! I released this change in 0.0.29.