Suppose that we have a class User, and UserBuilderin its own package, which we want to be the same and in a consistent state before the initialization, defined as follows:
public class User {
private final String firstName, lastName;
private final int age;
private final String adress;
protected User(UserBuilder buildUser) {
this.firstName = buildUser.lastName;
this.lastName = buildUser.lastName;
this.age = buildUser.age;
this.adress = buildUser.adress;
}
public String getFirstName() {
return firstName;
}
...
}
And the builder class is as follows:
public class UserBuilder {
public final String firstName;
public final String lastName;
public int age;
public String adress;
public UserBuilder(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public UserBuilder setAge(int age) {
this.age = age;
return this;
}
public UserBuilder setAdress(String adress) {
this.adress = adress;
return this;
}
public UserBuilder getUser() {
return this;
}
public User build() {
return new User(getUser());
}
}
And finally, we create a user in a class that is in another package:
public static void main(String[] args) {
User user = new UserBuilder("John","Doe")
.setAge(22)
.build();
}
Is this considered a safe and good design? If not, why?
source
share