Hi,

I've been using Guice over the past couple of years and it worked quite 
well for me. However, every once in a while I run across a recurring 
problem and I'd like to get your feedback on it. The problem arises when I 
run across a constructor that requires a mix of Guice-injected and 
user-supplied values. For example:

  public MyService(UriInfo uriInfo, String userName)

This is precisely the use-case AssistedInject is meant to address but the 
more I run into this code, the more I am leaning towards using the Service 
Locator pattern [1] instead. AssistedInject requires me to construct and 
bind one factory per class. This means that every time I add/remove a 
class, I need to add/remove a binding. It means every time I add/remove 
user-supplied parameters, I need to also add/remove parameters from the 
factory. Initially it didn't seem like a big deal but time I've questioned 
the cost/benefit of this approach. The resulting code is harder to read and 
maintain, and for what? Nowadays I replace:

  @Inject
  public MyService(First first, Second second, Third third, @Assisted 
String userName)

with

  @Inject
  public MyService(Injector injector, String userName)
  {
    this.first = injector.getInstance(First.class);
    this.second = injector.getInstance(Second.class);
    this.third = injector.getInstance(Third.class);
  }

and simply inject classes on-demand using injector. Essentially I'm using 
Guice as a Service Locator. The way I see it:

   - The classes/constructors are a lot easier to maintain.
   - No need to enumerate the injected parameters in the Javadoc. I've 
   always found it annoying to have the Javadoc cluttered with parameters the 
   user doesn't really care about (besides the fact it was a lot of work to 
   keep such documentation up-to-date).
   - This still implements the inversion of control pattern so the code is 
   easily testable.
   - The dependencies might not be listed as constructor parameters, but 
   they still visible near the top of the constructor.
   - To clarify, I only advocate this approach when mixing injected and 
   user-supplied parameters. I still use normal constructor injection when all 
   parameters come from Guice.

So really, what's the harm? I'd love to get your feedback on this.

Thanks,
Gili

[1] http://martinfowler.com/articles/injection.html#UsingAServiceLocator

-- 
You received this message because you are subscribed to the Google Groups 
"google-guice" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/google-guice/-/HSTXZ7On-acJ.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/google-guice?hl=en.

Reply via email to