How many constructors should a class have?

前端 未结 16 1921
一向
一向 2021-02-04 12:34

I\'m currently modifying a class that has 9 different constructors. Now overall I believe this class is very poorly designed... so I\'m wondering if it is poor design for a clas

16条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-04 12:39

    A constructor should have only those arguments which are mandatory for creating the instance of that class. All other instance variables should have corresponding getter and setter methods. This will make your code flexible if you plan to add new instance variables in the future.

    In fact following OO principle of -

    1. For each class design aim for low coupling and high cohesion
    2. Classes should be open for extension but closed for modification.

      you should have a design like -

      import static org.apache.commons.lang3.Validate.*; public class Employee { private String name; private Employee() {}

      public String getName() { return name; }

      public static class EmployeeBuilder { private final Employee employee;

      public EmployeeBuilder()
      {
          employee = new Employee();
      }
      
      public EmployeeBuilder setName(String name)
      {
          employee.name = name;
          return this;
      }
      
      public Employee build()
      {
          validateFields();
          return employee;
      }
      
      private void validateFields()
      {
          notNull(employee.name, "Employee Name cannot be Empty");
      }
      

      } }

提交回复
热议问题