In Part 1 and Part 2, I removed several static calls in my pizza program. The services class now benefits from an object-oriented design. Replacing static with non-static methods allows for polymorphism and that helps in testing:
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);
}
}`</pre>**Polymorphism and static factory methods**
Regrettably, the code still has an outstanding static method, the factory method `Invoice.create()`. The implementation of this method looks up the store address statically:
<pre class="prettyprint">`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());
}
}`</pre>I made the store address injectable in [part 2](http://publicobject.com/2007/07/refactoring-to-guice-part-2-of-n.html) so I just need to get that injectable value here. I start by nesting a factory interface inside `Invoice.java`:
<pre class="prettyprint">`class Invoice {
...
interface Factory {
Invoice create(List<PizzaSpec> pizzas, int deliveryDistance);
}
}`</pre>I Implement that interface as an anonymous inner class within my module:
<pre class="prettyprint">`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());
}
});
}
}`</pre>**About the factory's implementation**
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, `Provider`s 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 `Provider`s 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:
<pre class="prettyprint">`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);
}
}`</pre>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:
<pre class="prettyprint">`static class Invoice {
public Invoice(List<PizzaSpec> pizzas, int deliveryDistance,
_@Inject @StoreAddress_ Address storeAddress) {
}
...
}`</pre>and then we can bind the factory directly to the class it constructs:
<pre class="prettyprint">`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!