I have written a class using Joshua Bloch's Builder pattern, which is similar to this Pizza example:
public class Pizza {
private int size;
private boolean cheese;
private boolean pepperoni;
private boolean bacon;
public static class Builder {
//required
private final int size;
//optional
private boolean cheese = false;
private boolean pepperoni = false;
private boolean bacon = false;
public Builder(int size) {
this.size = size;
}
public Builder cheese(boolean value) {
cheese = value;
return this;
}
public Builder pepperoni(boolean value) {
pepperoni = value;
return this;
}
public Builder bacon(boolean value) {
bacon = value;
return this;
}
public Pizza build() {
return new Pizza(this);
}
}
private Pizza(Builder builder) {
size = builder.size;
cheese = builder.cheese;
pepperoni = builder.pepperoni;
bacon = builder.bacon;
}
}
but PMD reported 2 warnings:
Should I just ignore these warnings?
Another question: the private fields in class Pizza
and Builder
are duplicate. This will be annoying when the number of private fields getting bigger. Is there any way to avoid it?
About how to remove duplication.
I'll get more downvotes :) But maybe something like this?
class Pizza {
private int size;
private boolean cheese;
private boolean pepperoni;
private boolean bacon;
public static class Builder {
private Pizza pizza = new Pizza();
public Builder(int size) {
pizza.size = size;
}
public Builder cheese(boolean value) {
pizza.cheese = value;
return this;
}
public Builder pepperoni(boolean value) {
pizza.pepperoni = value;
return this;
}
public Builder bacon(boolean value) {
pizza.bacon = value;
return this;
}
public Pizza build() {
return pizza;
}
}
private Pizza() {
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With