The builder pattern and a large number of mandatory parameters

前端 未结 7 1951
甜味超标
甜味超标 2020-11-29 02:44

To date I use the following implementation of the builder pattern (as opposed to the implementation described here):

public class Widget {
    public static          


        
7条回答
  •  北海茫月
    2020-11-29 03:12

    I've been struggling lately to understand how the pattern is of any benefit when all your parameters are mandatory

    The pattern eases creation of immutable classes and promotes readable code. Consider the Person class below (with a conventional constructor and a builder).

    public static class Person {
    
        private static final class Builder {
            private int height, weight, age, income, rank;
            public Builder setHeight(final int height) { this.height = height; return this; }
            public Builder setWeight(final int weight) { this.weight = weight; return this; }
            public Builder setAge(final int age) { this.age = age; return this; }
            public Builder setIncome(final int income) {    this.income = income; return this; }
            public Builder setRank(final int rank) { this.rank = rank; return this; }
            public Person build() { return new Person(this); }
        }
    
        private final int height;
        private final int weight;
        private final int age;
        private final int income;
        private final int rank;
    
        public Person(final int height, final int weight, final int age, final int income, final int rank) {
            this.height = height; this.weight = weight; this.age = age; this.income = income; this.rank = rank;
        }
    
        private Person(final Builder builder) {
            height = builder.height; weight = builder.weight; age = builder.age; income = builder.income; rank = builder.rank;
            // Perform validation
        }
    
        public int getHeight() { return height; }
        public int getWeight() { return weight; }
        public int getAge() { return age; }
        public int getIncome() { return income; }
        public int getRank() {  return rank; }
    
    }
    

    Which method of construction is easier to comprehend?

    final Person p1 = new Person(163, 184, 48, 15000, 23);
    final Person p2 = new Person.Builder().setHeight(163).setWeight(184).setAge(48).
        setIncome(15000).setRank(23).build();
    

    One means of getting around this has been to logically group the parameters being passed in to their own classes

    Sure, this is the principle of cohesion and should be adopted irrespective of object construction semantics.

提交回复
热议问题