Lombok: Lombok Builder annotation should create a private constructor with a builder instance as the only argument

Created on 21 Jun 2018  路  2Comments  路  Source: projectlombok/lombok

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);
        }
    }
}

Most helpful comment

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.

All 2 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

merric picture merric  路  4Comments

rn4n picture rn4n  路  3Comments

Bryksin picture Bryksin  路  3Comments

delverdev picture delverdev  路  3Comments

x9nico picture x9nico  路  3Comments