Private fields in the Pizza and Builder classes are duplicated. This will be annoying when the number of private fields become larger. Is there any way to avoid this?
I personally get around this using the third private class of objects of static value, which contains all the fields and uses it both in the builder and in the main class (access to the field is processed by delegation). Of course, this can lead to bloating the count of the number of lines / classes, but it is invaluable if your builders are ultimately complicated by a large number of fields and checks.
In addition, it will not actually provide a static method for the Pizza class, which constructs a Pizza object with required fields. Unless, of course, you know what mandatory fields are, or are afraid that mandatory fields may change as your class evolves. If you think that as long as you can justify your actions after many thoughts (as Joshua Bloch does), you can safely ignore these warnings, knowing that you know what you are doing. :-)
Discarded fragment:
public class Pizza { private final PizzaVO vo; private static class PizzaVO { int size; boolean cheese; boolean pepperoni; boolean bacon; } public static class Builder { private final PizzaVO vo = new PizzaVO(); public Builder(int size) { vo.size = size; } public Builder cheese(boolean value) { vo.cheese = value; return this; } public Builder pepperoni(boolean value) { vo.pepperoni = value; return this; } public Builder bacon(boolean value) { vo.bacon = value; return this; } public Pizza build() { return new Pizza(vo); } } private Pizza(PizzaVO vo) { this.vo = vo; } public int getSize() { return vo.size; }
source share