You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Factories are often used because there are too many parameters and/or options to specify them:
new Factory().setBla(2).setFoo("yes").create();
instead of new Bar(2, "yes");
Can we specify some parameters as "optional", which will cause setter methods to be generated instead of a create() method which accepts all parameters?
Suggestion:
class Bar {
@AutoFactory(validate = validate)
public Bar(@Optional(default = getBla) D bla, R required) { ... }
/**
* Write any assertions that the factory's create() will call.
*/
static void validate(D bla, R required) {
Preconditions.assertState(...);
}
/**
* Create a value for "default" if not supplied
*/
static D getBla(R required) {
return new Proxy(C, R); // just an example!
}
}
will generate
class BarFactory {
private D bla = null;
@Inject
public BarFactory() {
}
public BarFactory setBla(D bla) {
this.bla = bla;
return this;
}
public Bar create(R required) {
if (bla == null) {
bla = Bar.getBla();
}
Bar.validate(D, R);
return new Bar(D, R);
}
}
Usage:
BarFactory bf = new BarFactory().setBla(b).create(R);
or
BarFactory bf = new BarFactory().create(R); // Uses default for "bla"
The text was updated successfully, but these errors were encountered:
You seem to be describing the Builder pattern, which is a bit different. In fact, for the example you give (with no injected constructor arguments), you can just use AutoValue's built-in Builder support ([https://github.com/google/auto/blob/master/value/userguide/builders.md](documentation here).
In the situation you allude to, one often defines a factory that accepts a value object in its create method. Thus, the code might look like
// no complex initialization
BarContext ctx = BarContext.builder().setBlah(1).setFoo(2).build();
// barFactory could have complex dependencies
Bar bar = barFactory.create(ctx);
AutoFactory and AutoValue already neatly support this use case.
Factories are often used because there are too many parameters and/or options to specify them:
new Factory().setBla(2).setFoo("yes").create();
instead of new Bar(2, "yes");
Can we specify some parameters as "optional", which will cause setter methods to be generated instead of a create() method which accepts all parameters?
Suggestion:
will generate
Usage:
or
The text was updated successfully, but these errors were encountered: