Java constructor parameters to resolve excessive -builder mode (effect java study notes 2)

First, the prospects:

  Normally we do not encounter such a situation, using a static factory method or constructor is enough. But they also have a limitation is that they do not scale well to the scene number of optional parameters. With the development of our business, some of the parameters in the java bean will be more and more, we add the constructor has also increased correspondingly. Think of a 10 constructor argument, I stomach.

  Since you want to use builder mode, we first need to know the shortcomings of the traditional method.


Second, scalable model constructor VS builder

  We have to speak in code examples

1, telescopic construction method

public class Student {
    private final String name; // required
    private final String sex;  // required
    private final int weight;  // optional
    private final int height;  // optional 
    private final int age;     // optional

    public Student(String name, String sex) {
        this(name, sex, 0);
    }
    
    public Student(String name, String sex, int w) {
        this(name, sex, w, 0);
    }
    
    public Student(String name, String sex, int w, int h) {
        this(name, sex, w, h, 0);
    }

    public Student(String name, String sex, int w, int h, int a) {
        this.name = name;
        this.sex = sex;
        this.weight = w;
        this.height = h;
        this.age = a;
    }
}
复制代码

When we want to create a Student instance, you can set all the parameters of the shortest enough with as follows:

Student student = new Student("小明", "男", 50, 150, 16);

  Under normal circumstances, this construction method may require a lot of you do not want to set a parameter (is not it a bit uncomfortable), with the increase of parameters, it will soon be out of control. (You will go crazy). First, it is difficult to understand this approach, if followed by a reverse two parameters, the compiler is not being given . Such as height and weight fill backwards, Zaoxin. . . . .

2, JavaBean model

  When faced with a number of optional parameters in the constructor, JavaBeans Another option mode, in this mode, calls a constructor to create a free parameter object, and then invoking the setter to set the required parameters and for each optional parameters:

public class Student {
    private  String name; // required
    private  String sex;  // required
    private  int weight;  // optional
    private  int height;  // optional
    private  int age;     // optional

    public Student() {}


    public void setName(String name) {
        this.name = name;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
复制代码

This mode one no disadvantage constructor. A little lengthy, but easy to create an instance, and easy to read

        Student student = new Student();
        student.setName("小明");
        student.setSex("男");
        student.setAge(16);
        student.setWeight(50);
        student.setHeight(150);
复制代码

  JavaBeans model itself has serious flaws. Since the constructor call is divided in a plurality of times, so during construction JavaBean may be in an inconsistent state. This class is not an option to perform consistency checks the validity of configuration parameters by parameters. Try to use an object in an inconsistent state and may cause the error bug-free code contains very different, it is difficult to debug. A related disadvantage is that, JavaBeans pattern precludes the possibility to make an immutable class, and the need to increase work on the part of the programmer to ensure thread safety

3, builder mode

  binding the model builder scalable security model construction method and readability JavaBean mode.

public class Student {
    private final String name;
    private final String sex;
    private  final int weight;
    private final int height;
    private  final int age;

    private Student(Builder builder) {
        this.name = builder.name;
        this.sex = builder.sex;
        this.weight = builder.weight;
        this.height = builder.height;
        this.age = builder.age;
    }
    
    public static class Builder {
        private final String name; // required
        private final String sex;  // required
        private int weight;  // optional
        private int height;  // optional
        private int age;     // optional

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

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

        public Builder setHeight(int height) {
            this.height = height;
            return this;
        }
        
        public Builder setAge(int age) {
            this.age = age;
            return this;
        }
        
        public Student build() {
            return new Student(this);
        }

    }
}
复制代码

  First, let me spray it, doubled the amount of code. But the Student class is immutable, all parameter default values ​​are in one place. builder's setter method returns the builder itself, this call can be linked together to generate a fluent API. Examples are as follows:

Student student = new Student.Builder("小明", "男").setWeight(50)
                .setHeight(150).setAge(16).build();
复制代码

  Code is easy to write, but more importantly is easy to read. Builder Python and Scala in analog mode named optional parameters. There is no concern to check the validity of


to sum up:

  builder a slight advantage over the construction method is, builder can have multiple variable parameters, since each parameter is specified in its own method.

  Builder mode is very flexible. A plurality of individual objects can be constructed builder reused. builder's parameters can be adjusted between calls to build methods to change the object created. builder can automatically fill in some properties when you create an object, creating an object, for example, each time increasing sequence number.

  Builder model also has drawbacks. To create an object, you must first create its builder. Although the cost of creating this builder is unlikely to be noticed in practice, but problems may arise in the performance of critical situations. Moreover, builder mode is more verbose than stretching constructor mode, so only if there is sufficient if the parameters are worth using it, such as four or more. But remember, if you want to add more parameters in the future. However, if you start from a constructor or static factory and switch to the builder, when class time to the evolution of the number of parameters out of control, out of date constructor or static factory will face an embarrassing situation. Therefore, it is best to create a builder from the beginning.

  In conclusion, when designing class constructor or static parameters of more than a few plants, Builder mode is a good choice, especially if many parameters are the same or alternative type. Client code than using a telescopic construction method (telescoping constructors) easier to read, and safer than builder JavaBeans.

ps: If there is a book club reading micro-channel can be micro-channel study group portal to find organizations.

Guess you like

Origin juejin.im/post/5d5647c6f265da03c5030b53