samedi 9 juillet 2016

Is this workaround for not duplicating class attributes for builder pattern ok?

I was reading about the builder pattern and one disadvantage is the fact that you have to duplicate the class attributes in both class and builder class (really boring!).

Like this:

public class Person {
    private String name;
    private int age;

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

    public String getName() { return name; }

    public int getAge() { return age; }

    public static class Builder {
        private String name; // duplication here
        private int age;     // duplication here

        public Builder name(String name) { this.name = name; return this; }

        public Builder age(int age) { this.age = age; return this; }

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

But what if I make something like this:

public class Person {
    private String name;
    private int age;

    private Person(){}
    private Person(Builder b) {
        this.name = b.person.name;
        this.age = b.person.age;
    }

    public String getName() { return name; }

    public int getAge() { return age; }

    public static class Builder {
        private final Person person = new Person(); // here! should it be static, though?

        public Builder name(String name) { person.name = name; return this; }

        public Builder age(int age) { person.age = age; return this; }

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

Is there any issue with this approach? This seems to get rid of that disadvantage.

Aucun commentaire:

Enregistrer un commentaire