Java unfortunately doesn't support optional parameters. One solution to this might be to use a Builder Pattern. You create a separate UserBuilder
class, which only takes the required arguments in its constructor. Other arguments are passed through set functions. This also allows you to give some of the parameters default values. When all the parameters are set, you call UserBuilder.getUser()
and your User
object is created for you. Typically you also make sure the User
constructor is not available elsewhere.
class User{
String name, email, bio, address, phoneNumber;
int age;
User(String name, String email, int age, String bio, String address, String phoneNumber){
this.name = name;
this.email = email;
this.age = age;
this.bio = bio;
this.address = address;
this.phoneNumber = phoneNumber;
}
}
class UserBuilder{
String name, email, bio, address, phoneNumber;
int age;
public UserBuilder(String name, String email){
this.name = name;
this.email = email;
}
public void setBio(String bio) {
this.bio = bio;
}
public void setAddress(String address) {
this.address = address;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setAge(int age) {
this.age = age;
}
public User getUser(){
return new User(name, email,age,bio,address,phoneNumber);
}
}
For example, this is how you would create a User object with the builder class if you only wanted to set name, age, and email:
UserBuilder builder = new UserBuilder(name,email);
builder.setAge(38);
builder.getUser();