直接依存のみを注入せよ
他のオブジェクトを取得するためだけのオブジェクトを注入することを避けよう。 例えば、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;
} 