Is it wrong to have a lot of parameters inside a constructor? Like 10 to 15 parameters? Because I was designing a class where a constructor will have lots of parameters, for example, a Person
class.
My example person class has 6 parameters in its constructor:
public class Person { private String fName; private String lName; private String mInitial; private int age; private String contactNumber; private String emailAddress; public Person(String fName, String lName, String mInitial, int age, String contactNumber, String emailAddress) { //insert rest of code here } }
Is that wrong? Creating lots of parameters for a constructor?
Then I am planning to create a class named Employee
, then extending it to person class, then it will have a long constructor as well.
The thing that worries me about is the practice, is this good or what? Any other suggestions?
You might actually come close to the technical limit of 255 parameters for constructors and other units.
This method has four parameters: the loan amount, the interest rate, the future value and the number of periods.
There can be multiple constructors in a class. However, the parameter list of the constructors should not be same. This is known as constructor overloading.
You can have constructors with multiple parameters, but also have a constructor with only the minimum parameters.
In general, if you find yourself have too many parameters, that means you don't have enough low-level classes. In your case, you could have a class Name { /* fname, lname, initial, */ }
and perhaps a class Contact { /* email, phone */ }
When you extend your class, have the constructor take the base as one parameter, and then add the new extra parameters. (You probably mean Employee will extend Person, rather than vice versa, so public Employee (Person person, Company company, String employeeId) { super(person); this.company = company; this.employeeId = employeeId; }
Good question!
Instead of using telescoping constructor pattern, use builder pattern
public class Person { private final String fName; private final String lName; private final String mInitial; private final int age; private final String contactNumber; private final String emailAddress; public Person(PersonBuilder builder) { //insert rest of code here fName = builder.fName; ... } public static class PersonBuilder { private String fName; private String lName; private String mInitial; private int age; private String contactNumber; private String emailAddress; // setter methods public PersonBuilder setFirstName(String name) { fName = name; return this; } ... // build method public Person build() { return new Person(this); } } }
...
Person p = new PersonBuilder() .setFirstName("") // set all the setter methods .build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With