Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AutoFactory: optional parameters #102

Open
cgrushko opened this issue May 14, 2014 · 1 comment
Open

AutoFactory: optional parameters #102

cgrushko opened this issue May 14, 2014 · 1 comment

Comments

@cgrushko
Copy link
Contributor

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"
@clintonc
Copy link

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.

@raghsriniv raghsriniv added the P3 label Jun 24, 2019
@kluever kluever added the type=addition A new feature label Aug 16, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants