|
MinimizeMutability
Minimize mutabilityWherever possible, use constructor injection to create immutable objects. Immutable objects are simple, shareable, and can be composed. Follow this pattern to define your injectable types: public class RealPaymentService implements PaymentService {
private final PaymentQueue paymentQueue;
private final Notifier notifier;
@Inject
RealPaymentRequestService(
PaymentQueue paymentQueue,
Notifier notifier) {
this.paymentQueue = paymentQueue;
this.notifier = notifier;
}
...All fields of this class are final and initialized by a single @Inject-annotated constructor. Effective Java discusses other benefits of immutability. Injecting methods and fieldsConstructor injection has some limitations:
Method injection is most useful when you need to initialize an instance that is not constructed by Guice. Extensions like AssistedInject and Multibinder use method injection to initialize bound objects. Field injection has the most compact syntax, so it shows up frequently on slides and in examples. It is neither encapsulated nor testable. Never inject final fields; the JVM doesn't guarantee that the injected value will be visible to all threads. |
Sign in to add a comment