Constructor with many parameters
I have a class with (say) 50 fields. I only use a few of these to deploy the program to each user. Is there a way to make the constructor generic but deployment specific?
eg
public class Employee{
private String id = "default";
private String empcat = "default";
private String empfam = "default";
private String phychar = "default";
private String othchar = "default";
private String shoesty = "default";
private Double shoesiz = 0.0;
private String shoesty = "default";
private Double shirsiz = 0.0;
private String shirsty = "default";
.........50 other fields..
}
"User / Client 1" - only wants to use the shoe program and thus creates an object: Employee obemp = new employee ("John", 11.5, Docker); (i.e. id, shoes and showy)
User / Client 2 - only wants to use the shirt program and thus creates an object: Employee obemp = new employee ("John", 42, ABC); (like id, shirsiz and shirsty)
User / Client 3 - only wants to use the family program and thus creates an object with: Employee obemp = new employee ("John", "Smith"); (i.e. id, empfam)
The order of fields when creating an object can vary depending on how it is used in the model.
source to share
First of all, I suggest breaking your main class into smaller pieces that manage the data that usually goes together (shoe info, shirt info, family info, etc.).
Secondly, I suggest that you provide clients with a builder template to make it easier for them to create an object with only the parts they are likely to need. So they can do something like this:
Employee emp = new EmployeeBuilder("John")
.withShirtInfo(shirsiz, shirsty)
.build();
source to share
There is no generic way to do this in Java core. But you can use a design pattern like: -builder.
You can also create Employee
with minimal criteria, for example - id
. We can assume that everyone Employee
has id
. So create Employee
with the help of id
with the help of the designer Employee(String id)
-
public class Employee{
//all properties
public Employee(String id){
this.id = id;
}
//setter methods
}
Suppose you created Employee
like this -
Employee employee = new Employee("eng134");
After that, you can set only the required property for the object Employee
using the setting methods -
employee.setShoesiz(9);
employee.setShirsiz(26);
source to share