AutoFactory: optional parameters
- Dominant language
- Java
- Stars
- 10.6k
- Forks
- 1.2k
- Avg merge
- 6h 32m
- Merged PRs (30d)
- 13
Description
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"
```
Contributor guide
Assessment
This issue has not been assessed yet.