My favorites | Sign in
Google
                
Search
for
Updated Apr 16, 2009 by limpbizkit
InjectOnlyDirectDependencies  

Inject only direct dependencies

Avoid injecting an object only as a means to get at another object. For example, don't inject a Customer as a means to get at an Account:

public class ShowBudgets { 
   private final Account account; 

   @Inject 
   ShowBudgets(Customer customer) { 
     account = customer.getPurchasingAccount(); 
   } 

Instead, inject the dependency directly. This makes testing easier; the test case doesn't need to concern itself with the customer. Use an @Provides method in your Module to create the binding for Account that uses the binding for Customer:

public class CustomersModule extends AbstractModule { 
  @Override public void configure() {
    ...
  }

  @Provides 
  Account providePurchasingAccount(Customer customer) { 
    return customer.getPurchasingAccount();
  }

By injecting the dependency directly, our code is simpler.

public class ShowBudgets { 
   private final Account account; 

   @Inject 
   ShowBudgets(Account account) { 
     this.account = account; 
   } 

Comment by brhargett, May 20, 2009

If you want the account of a certain customer how would you handle that outside of doing it the 1st way (customer.getAccount())?

Comment by ffaber, Aug 06, 2009

You would bind the Account and have that injected in. If you know your customer at configure() time, then you'll know your Account.

As a simple example, you could have:

bind(Account.class)

.toProvider(new Provider<Account>() {
@Inject Customer customer;
@Override public Account get() {
return customer.getAccount();
}
});


Sign in to add a comment