Deletions are marked like this. | Additions are marked like this. |
Line 14: | Line 14: |
変わり依存を直接注入すべきである。これによってテストが簡単になる。 | その代わりに依存を直接注入すべきである。これによってテストが簡単になる。 |
Line 17: | Line 17: |
Use an @Provides method in your Module to create the binding for Account that uses the binding for Customer: |
モジュールの中で@Providesを使ってAccountのバインディングを作成しよう。 そして、その中でCustomerのバインディングを用いる。 |
直接依存のみを注入せよ
他のオブジェクトを取得するためだけのオブジェクトを注入することを避けよう。 例えば、Accountを取得するためだけにCustomerを注入することはしないように。
public class ShowBudgets { private final Account account; @Inject ShowBudgets(Customer customer) { account = customer.getPurchasingAccount(); }
その代わりに依存を直接注入すべきである。これによってテストが簡単になる。 テストケースはCustomerについて考慮する必要がなくなる。
モジュールの中で@Providesを使ってAccountのバインディングを作成しよう。 そして、その中で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; }