I’m using a builder pattern (as explained in Joshua Bloch’s Effective Java) for a few things, and there’s a particularly annoying repetition involved:
public class Foo {
private String name;
private int age;
public static class Builder implements IBuilder {
private String name;
private int age;
Builder name(String value) {
name = value;
return this;
}
Builder age(int value) {
age = value;
return this;
}
Foo build() {
return new Foo(this);
}
}
private Foo(Builder builder) {
name = builder.name;
age = builder.age;
}
}
It’s small, but annoying. I have to declare the variable in each class. I tried creating a class with the fields and extending that class, but I got the error: {variable_name} has private access in {class_name}.
Is there a way to do this, without making the variables public?
If your builders are purely for capturing a bunch of state (and not doing any intermediate computation), you can solve the repetition by just defining the builder interface, then writing a Java proxy generator.
If you were to do this, you couldn’t rely on the outer class having access to the builder (inner) class’s private fields. To work around that, you would need to define accessors for each field, too. So for example:
Alternatively, your builder could expose all the fields in a
Mapor similar structure. Using that route, your interface would only need the chaining setters. But you give up compile time checking of all your field usages within the constructor. IMHO, too big a compromise.