I want to know if my implementation of the builder object has disadvantages compared to the builder object implementation I see on most site's. I know it's overkill to implement a builder object for a class with only 2 fields, but these are just examples and meant to be small.
My implementation:
public class User {
private String firstname;
private String lastname;
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
private User(){}
public static class Builder{
private final User user;
public Builder(){
user = new User();
}
public Builder firstname(String firstname){
user.firstname = firstname;
return this;
}
public Builder lastname(String lastname){
user.lastname = lastname;
return this;
}
public User build(){
return user;
}
}
}
Builder object as found on the internet (example1 example2):
public class User {
private String firstname;
private String lastname;
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
private User(Builder builder){
this.firstname = builder.firstname;
this.lastname = builder.lastname;
}
public static class Builder{
private String firstname;
private String lastname;
public Builder firstname(String firstname){
this.firstname = firstname;
return this;
}
public Builder lastname(String lastname){
this.lastname = lastname;
return this;
}
public User build(){
return new User(this);
}
}
}
The second implementations seems cumbersome, cause the builder needs to have exactly the same field as the object it will be building (read: writing the same code twice).
It also seems more naturally (to me) that the builder creates the new User
and populates its fields, instead off calling the constructor of the User
with it's own instance.
Both examples can be tested with:
public static void main(String[] args) {
User u = new User.Builder().firstname("Tom").lastname("Jonckheere").Build();
System.out.println(u.getFirstname());
System.out.println(u.getLastname());
}
So my question is: What are the disadvantages of my implementation of the builder object? I can't really tell any (and I'm not saying there aren't any) so I would like to hear some feedback! Or is my code also a valid implementation of the builder object?
The difference in the implementations are that if you want to create multiple equal (or similar) but not same objects, you'll have to create a new Builder
whereas with the other implementation you can do this:
Builder b = new User.Builder();
User john = b.firstName("John").lastName("Smith").build();
User jack = b.firstName("Jack").build();