Revision 1 as of 2009-12-12 05:29:11

Clear message
Locked History Actions

guice/Manual/BestPractices/InjectOnlyDirectDependencies

直接依存のみを注入せよ

他のオブジェクトを取得するためだけのオブジェクトを注入することを避けよう。 例えば、Accountを取得するためだけにCustomerを注入することはしないように。

public class ShowBudgets { 
   private final Account account; 

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

変わり依存を直接注入すべきである。これによってテストが簡単になる。 テストケースは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();
  }

依存を直接注入することにより、コードはシンプルになる。

public class ShowBudgets { 
   private final Account account; 

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