Java constructor with large arguments or Java bean getter/setter approach

后端 未结 18 2075
清歌不尽
清歌不尽 2020-12-12 21:29

I can\'t decide which approach is better for creating objects with a large number of fields (10+) (all mandatory) the constructor approach of the getter/setter. Constructor

18条回答
  •  有刺的猬
    2020-12-12 22:12

    I would implement the builder pattern like this:

    package so1632058;
    
    public class MyClass {
      private final String param1;
      private final String param2;
    
      MyClass(Builder builder) {
        this.param1 = builder.param1;
        this.param2 = builder.param2;
      }
    
      public String getParam1() {
        return param1;
      }
    
      public String getParam2() {
        return param2;
      }
    
      @SuppressWarnings("hiding")
      public static final class Builder {
        String param1;
        String param2;
    
        public Builder param1(String param1) {
          this.param1 = param1;
          return this;
        }
    
        public Builder param2(String param2) {
          this.param2 = param2;
          return this;
        }
    
        public MyClass toMyClass() {
          return new MyClass(this);
        }
      }
    }
    

    And then have the following code to use it:

    package so1632058;
    
    public class Main {
    
      public static void main(String[] args) {
        MyClass.Builder builder = new MyClass.Builder();
        builder.param1("p1").param2("p2");
        MyClass instance = builder.toMyClass();
        instance.toString();
      }
    
    }
    

    Some notes:

    • There are no methods with many parameters.
    • The additional checking can be done in the MyClass constructor.
    • I made the constructor's visibility package-wide to avoid the "synthetic-access" warning.
    • Same for the builder's instance fields.
    • The only way to construct an instance of MyClass is via the Builder.

提交回复
热议问题