java nested builder pattern duplicate fields

Viewed 1723

The nested builder patterns that I've come across online usually have something like this:

class Person{

    private int id;
    private String name;
    private int age;
    ... so on

    private Person(Builder builder){
        this.id = builder.id;
        this.name = builder.name;
        this.age = builder.age;
    }

    public static class Builder{

        private int id;
        private String name;
        private int age;
        ... so on

        public Builder id(int id){
            this.id = id;
            return this;
        }
        public Builder name(String name){
             this.name = name;
             return this;
        }
        .... so on

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

    }

}

My question is, is it necessary to duplicate fields in Person and Builder? It seems like a lot of redundant code. And my second question is, would the following code be a viable replacement, why or why not?

class Person{

    private int id;
    private String name;
    private int age;
    ... so on

    private Person(){}

    public static class Builder{

        private Person person = new Person();

        public Builder id(int id){
            this.person.id = id;
            return this;
        }
        public Builder name(String name){
             this.person.name = name;
             return this;
        }
        .... so on

        public Person build(){
            return person;
        }
        // UPDATED -- another build method
        public Person build(){
            Person built = this.person;
            this.person = new Person();
            return built;
        }

    }

}

Note: I understand this topic may be opinionated and there may not be a "right" answer, but I just want to hear different ideas and opinions. I'm not looking for the ultimate truth.

1 Answers
Related