What is dependency injection? - “the practice of injecting the dependencies to class instead of
hardcoding them in the class”
Enables truly isolated unit tests
Enables re-usability of individual objects
A small but crucial change
The test becomes less complex
Example #2 Service Object
A controller for a fruit search
First version of the service object
A more DI version of the service object
A new search category gets added, but thanks to DI we can easily leverage the existing service object.
ComplexProduceSearch.new is repeated, so let’s remove duplication, and make the service object take advantage of being an instance.
With these changes the hardcoded dependency has become a runtime dependency. Now we are programming to an
interface instead of an implementation.
Ducks and Mallards
Not OO, more like a namespaced procedure, implementation hard to refactor
More or less the same as before, though there is an instance. But this instance isn’t reusable.
Instantiation and invocation have been separated. The object can reused for different inputs.
You can take this even further in your application by creating instantiation as a separate concern.
But how to get it into Rails? Stephen suggests to add a constant to the initializers
This sounds like a resonable approach, but it breaks Rails reloading.
To make a ruby object a singleton (thanks to our functional approach, we want to use the same instance through
the lifecycle of our application), we can just include the Singleton
Though still leaves us with the dependency to the concrete App class.
The mallard approach
With dependency injection
Still coupled with the interface of the user_class
Lets abstract away the interface to the user_class
User_builder can be anything that responds to #call (procs, blocks, lambdas)…
..or for example the #method method
This user_builder can be easily replaced with a more comples object later.
Benefits of DI
More focused and faster tests
More flexible code
Code that can do different things when introduced to new collaborators
Reduced need to change existing objects
A clear path for acheiving the ‘O’, ‘I’ and ‘D’ of SOLID