Chapter 9, Just-in-Time Dependency Injection

1. How does Just-in-Time (JIT) dependency injection differ from constructor injection?

This depends a lot on how the constructor injection is being used; in particular, how many different implementations of the dependency exist. If there is only one production implementation of a dependency, then they are functionally equivalent. The only difference is UX (that is, whether there is one less dependency to inject into the constructor).

If, however, there is more than one production implementation, then JIT dependency injection cannot be used.

 

2. When working with optional dependencies, why is using a NO-OP implementation important?

When a member variable is not set by the constructor, then it is effectively optional. We cannot, therefore, be sure that the value has been set and not nil. By adding a NO-OP implementation of the optional dependency and automatically setting it to the member variable, we are able to assume that the dependency is always non-nil and we can forgo the need for guard clauses.

3. What are the ideal use cases for JIT injection?

JIT injection is ideal for the following:

  • Replacing a dependency that would otherwise have been injected into the constructor and of which there is only one production implementation
  • Providing a layer of indirection or abstraction between an object and a global singleton, particularly when we want to swap out the global singleton during testing
  • Allowing dependencies to be optionally provided by the user

 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.57.164