Wojciech Owczarczyk
Wojciech Owczarczyk

Reputation: 5735

Immutable objects builder

Would it be considered a good practice to store the builder instance inside the instance that it has built? The thing is that I quite often find myself in a situation when I need to create a very similiar object to the one that I already have. Presumable this object has many 8-10 fields. Normally, with a mutable object I would have just used setter.

For instance, lets take the classic Bloch's NutricionFacts example:

public class NutritionFacts {
    private final int servingSize;
    private final int servings;
    private final int calories;
    private final int fat;
    private final int sodium;
    private final int carbohydrate;

    private final Builder builder;

    public static class Builder {
        // Required parameters
        private final int servingSize;
        private final int servings;
        // Optional parameters - initialized to default values
        private int calories = 0;
        private int fat = 0;
        private int carbohydrate = 0;
        private int sodium = 0;

        public Builder(int servingSize, int servings) {
            this.servingSize = servingSize;
            this.servings = servings;
        }
        public Builder calories(int val)
        { calories = val; return this; }
        public Builder fat(int val)
        { fat = val; return this; }
        public Builder carbohydrate(int val)
        { carbohydrate = val; return this; }
        public Builder sodium(int val)
        { sodium = val; return this; }

        public NutritionFacts build() {
            return new NutritionFacts(this);
        }
    }

    private NutritionFacts(Builder builder) {
        servingSize = builder.servingSize;
        servings = builder.servings;
        calories = builder.calories;
        fat = builder.fat;
        sodium = builder.sodium;
        carbohydrate = builder.carbohydrate;
        this.builder = builder;
    }
}

I have modified it a bit so I can access the builder instance if I want to make a simmiliar copy in the future?

What do you think?

Upvotes: 4

Views: 2127

Answers (1)

ante
ante

Reputation: 1095

What happens if you reuse the Builder to build a second instance? The Builder in the first instance would then produce instances similar to the second instance. Probably not what you expected.

I would suggest an option to create the Builder with a template instance.

    public Builder(NutritionFacts template) {
        this.servingSize = template.getServingSize();
        ...
    }

Upvotes: 7

Related Questions