Revision 2 as of 2009-12-14 06:17:36

Clear message
Locked History Actions

guice/RefactoringToGuice/part3

パート3

パート1,2で、ピザプログラムからいくつかの静的呼び出しを取り除いた。 今やサービスクラスはオブジェクト指向デザインの恩恵を受けられるようになった。 非静的メソッドから静的メソッドに置き換えればポリモフィズムを利用することができるんで、テストが楽になるんだ。

public class PizzaServices {
  private final Oven currentOven;
  private final Address storeAddress;
  private final GeographyServices geographyServices;

  @Inject
  public PizzaServices(Oven currentOven,
      @StoreAddress Address storeAddress,
      GeographyServices geographyServices) {
    this.currentOven = currentOven;
    this.storeAddress = storeAddress;
    this.geographyServices = geographyServices;
  }

  public Order createOrder(List<PizzaSpec> pizzas, Customer customer) {
    Directions directions = geographyServices.getDirections(
      storeAddress, customer.getDeliveryAddress());

    if (directions == null || directions.getLengthInKm() > MAX_DISTANCE) {
      throw new InvalidOrderException("Cannot deliver to , " +
          customer.getDeliveryAddress());
    }

    int arrivalTime = TIME_TO_PREPARE
        + currentOven.schedule(TIME_TO_PREPARE, pizzas)
        + directions.estimateTravelTime();

    Invoice invoice = Invoice.create(pizzas, directions.getLengthInKm());
    return new Order(pizzas, invoice, arrivalTime, customer, directions);
  }
}

ポリモフィズムと静的ファクトリメソッド

残念だな、このコードにはまだ静的メソッドが残ってる。 ファクトリメソッドのInvoice.create()がそれだ。 実装を見てみると、このメソッドの中でまたまた静的にお店の住所を調べるなんてことをしてやがる。

class Invoice {
  public Invoice(List<PizzaSpec> pizzas, int deliveryDistance,
      Address storeAddress) {
  }
  static Invoice create(List<PizzaSpec> pizzas, int deliveryDistance) {
    return new Invoice(pizzas, deliveryDistance, PizzaStore.getStoreAddress());
  }
}

パート2でお店のアドレスを注入可能にしたわけなんだけど、それがここにも必要ってわけ。

まず、Invoice.javaの中にファクトリインターフェースを作っておこう。

class Invoice {
  ...
  interface Factory {
    Invoice create(List<PizzaSpec> pizzas, int deliveryDistance);
  }
}

このインターフェースをモジュールの中で匿名クラスとして実装する。

static class PizzaModule extends AbstractModule {
  protected void configure() {
    ...
    bind(Invoice.Factory.class).toInstance(new Invoice.Factory() {
      @Inject @StoreAddress Provider<Address> storeAddressProvider;
      public Invoice create(List<PizzaSpec> pizzas, int deliveryDistance) {
        return new Invoice(pizzas, deliveryDistance, storeAddressProvider.get());
      }
    });
  }
}

ファクトリの実装について

Everything bound via .toInstance() is injected by Guice when the Injector is created. That way, factories and providers can depend on services provided by other modules. Although constructor-injection is generally preferred, field injection is sufficient in this case.

Within the factory implementation, I bind a Provider<Address> rather than the address directly. This isn't strictly necessary because the address is a constant. But in general, Providers should always be used within factories. This ensures that I always get the correct instance, even if it depends on scope or context. I always use Providers within my implementations of Factory and Provider.

Using the injected factory

To replace the static Invoice.create() method call with the factory, I inject it:

public class PizzaServices {
  private final Oven currentOven;
  private final Address storeAddress;
  private final GeographyServices geographyServices;
  private final Invoice.Factory invoiceFactory;

  @Inject
  public PizzaServices(Oven currentOven,
      @StoreAddress Address storeAddress,
      GeographyServices geographyServices,
      Invoice.Factory invoiceFactory) {
    this.currentOven = currentOven;
    this.storeAddress = storeAddress;
    this.geographyServices = geographyServices;
    this.invoiceFactory = invoiceFactory;
  }

  public Order createOrder(List<PizzaSpec> pizzas, Customer customer) {
    ...
    Invoice invoice = invoiceFactory.create(pizzas, directions.getLengthInKm());
    return new Order(pizzas, invoice, arrivalTime, customer, directions);
  }
}

Now I can test the PizzaServices class without first preparing the static call to PizzaStore.getStoreAddress(). The code makes no static method calls and Guice does the wiring.

Looking forward: Simplifying the factory's implementation I've had to write a lot of code to implement the Invoice.Factory anonymous inner class. This is the best design, but it's more complex than the static method call. Better code should be easier to write otherwise I usually get lazy and revert to the static factory.

In the next release of Guice, user-defined factory interfaces will be supported. We first annotate the Invoice constructor's injected parameter:

static class Invoice {
  public Invoice(List<PizzaSpec> pizzas, int deliveryDistance,
      @Inject @StoreAddress Address storeAddress) {
  }
  ...
}

and then we can bind the factory directly to the class it constructs:

static class PizzaModule extends AbstractModule {
  protected void configure() {
    ...
    bind(Invoice.Factory.class).toFactoryFor(Invoice.class);
  }
}

This is equivalent to our factory inner class, but much more concise. If we change the signature of the Invoice constructor to add or remove injectable paramters, we don't need to update the factory interface.

Guice uses Java's dynamic proxy mechanism to implement the factory interface at runtime. It aggregates the factory method's parameters with injected parameters from the Injector to build the instance at create time.

If you can't wait for Guice 2.0, there's a similar API called AssistedInject that works with Guice 1.1.

Series Conclusion

Now I've removed all the static calls, and the PizzaServices class is perfectly polymorphic and totally testable. In this series, I've demonstrated constant injection, annotations and factory injection.

Replacing static, global code with testable polymorphic code is Guice's core competency. It allows me to decouple interface from implementation. It automatically wires my dependencies for me. If you want to embrace object-oriented design, guicify your app!