Eduardas Šlutas
Eduardas Šlutas

Reputation: 307

Updating an object with builder pattern

I recently found about this pattern and tried to implement it into my project. It does what it suppose to do. However, tried to find a nice solution to update it. Came up with one solution and I would like to know if it is "acceptable".

Only one difference which I did is I created another constructor inside Builder class which takes calling object as parameter:

public Builder (User user) {
    this.userID = user.getUserID();
    this.userName = user.getUserName();
    ...
    //and so on

and in main method

creating an object:

User user = new User.Builder("mandatory params")
                    .email("some email")
                    .build();

and update:

user = new User.Builder(user).phoneNumber("my number").build();

Is this approach acceptable?

Upvotes: 5

Views: 10523

Answers (2)

Navneet kumar
Navneet kumar

Reputation: 1964

You should use setters and getters whether or not you have the object empty or partially filled - it doesn't matter.

Also in my opinion it's better to use jackson objectMapper. Compared to builder pattern, it automatically handles new parameters without adding extra lines of code in the builder pattern and also it's more clean code.

Upvotes: 0

Kartik
Kartik

Reputation: 7917

This is good if you want to create a new user with fields copied from another user, with some changes:

anotherUser = new User.Builder(user).phoneNumber("my number").build();

But if you are assigning the new object back to the user variable, it suggests that you are updating the existing user. To update, you are creating a whole new object and copying fields, which is very inefficient. You should use setters.

Upvotes: 4

Related Questions