How many constructor arguments is too many?

前端 未结 15 1239
[愿得一人]
[愿得一人] 2020-11-29 15:03

Let\'s say you have a class called Customer, which contains the following fields:

  • UserName
  • Email
  • First Name
  • Last Name

15条回答
  •  Happy的楠姐
    2020-11-29 15:42

    Two design approaches to consider

    The essence pattern

    The fluent interface pattern

    These are both similar in intent, in that we slowly build up an intermediate object, and then create our target object in a single step.

    An example of the fluent interface in action would be:

    public class CustomerBuilder {
        String surname;
        String firstName;
        String ssn;
        public static CustomerBuilder customer() {
            return new CustomerBuilder();
        }
        public CustomerBuilder withSurname(String surname) {
            this.surname = surname; 
            return this; 
        }
        public CustomerBuilder withFirstName(String firstName) {
            this.firstName = firstName;
            return this; 
        }
        public CustomerBuilder withSsn(String ssn) {
            this.ssn = ssn; 
            return this; 
        }
        // client doesn't get to instantiate Customer directly
        public Customer build() {
            return new Customer(this);            
        }
    }
    
    public class Customer {
        private final String firstName;
        private final String surname;
        private final String ssn;
    
        Customer(CustomerBuilder builder) {
            if (builder.firstName == null) throw new NullPointerException("firstName");
            if (builder.surname == null) throw new NullPointerException("surname");
            if (builder.ssn == null) throw new NullPointerException("ssn");
            this.firstName = builder.firstName;
            this.surname = builder.surname;
            this.ssn = builder.ssn;
        }
    
        public String getFirstName() { return firstName;  }
        public String getSurname() { return surname; }
        public String getSsn() { return ssn; }    
    }
    
    import static com.acme.CustomerBuilder.customer;
    
    public class Client {
        public void doSomething() {
            Customer customer = customer()
                .withSurname("Smith")
                .withFirstName("Fred")
                .withSsn("123XS1")
                .build();
        }
    }
    

提交回复
热议问题