Why We Should Inject Dependencies
Dependency Injection frameworks have been around for some time, but Ruby developers have typically shied away from using them, likely due to the perception that it introduces unnecessary complexity. However, this perceived simplicity often comes at a cost, as this document will illustrate. Ruby's inherent flexibility enables a more approachable Dependency Injection (DI) implementation compared to languages like Java.
A common pattern in Ruby code involves passing object parameters as a mix of initialization parameters and method arguments, without a clear distinction between the two. For instance, consider the following imaginary code snippet where @email and @password are initialized as instance state for the class:
```ruby
class UserRegistration
def initialize(@email, @password)
# Code...
end
end
```
How often should we assume these values will change? Is it reasonable for these values to persist across multiple calls? In the context of a controller, we might find that `@email` and `@password` are derived from user input, and thus, require reinitializing the values for every signup. The `UserRegistration` instance is discarded immediately after computation. Why set up persistent state in an object that is immediately discarded?
These parameters should be treated as arguments, not dependencies. The class utilizes several external interfaces, such as EmailValidator, BCrypt::Password, UserRepository, and ConfirmationMailer, which are constants and do not change between calls. These dependencies are referenced directly in the implementation code, making it challenging to replace them in test scenarios.
If the `EmailValidator` changes its rules, causing a test email to fail, the test might fail due to unrelated reasons, such as the failure of the test email. To address this issue, a better approach is needed to replace these with test doubles.
In Ruby, objects are at the core of the design. Every interaction involves an object, and classes facilitate the definition of a repeatable pattern for creating objects of a particular type. However, these class instances are treated as separate entities. When one object interacts with another, a dependency relationship is established. We refer to these coordinating objects.
Managing complexity in a system primarily involves limiting these dependency relationships. If coordinating objects may be referenced at any point within an object, determining the totality of its dependencies becomes more difficult. Declaring all coordinating objects as explicit dependencies at the top allows for easier visual determination of a class's dependencies.
In the given example, determining the dependencies of the `UserRegistration` class is straightforward – it depends on `EmailValidator`, `BCrypt::Password`, `UserRepository`, and `ConfirmationMailer`, all of which are explicitly listed.
Introducing explicit dependencies at the top of a class simplifies the process of identifying an object's dependencies at a glance. This approach addresses the issue of managing complexity in larger classes where dependencies are spread throughout. It becomes increasingly challenging to comprehend how each pattern would scale when faced with larger classes where dependencies are dispersed.
In situations where a requirement arises that staff emails need to use a stronger digest algorithm, the original approach would necessitate changing the implementation. However, by injecting dependencies, this change can be achieved by simply passing in a different dependency. This construction allows for decoupling class initialization from its usage. To initialize an object using injected dependencies, the `initialize` method serves as the interface for injecting dependencies into the object.
When validating the behavior of code, it is crucial to test the behavior independently of the implementation. By injecting dependencies, we can replace them with test doubles, enabling us to test the validation behavior in isolation. For example, we can pass in an alternate implementation of `EmailValidator` to always pass or always fail the test, thereby isolating the validation behavior from the implementation details.
The `initialize` method can become cumbersome when an object has numerous dependencies, as it requires defining keyword arguments and assigning each keyword argument to an instance variable. To alleviate this redundancy, the `dry-initializer` gem provides a solution by defining options as keyword arguments and providing an instance method to access the values. This approach not only reduces redundancy but also allows for type-checking.
However, when objects need to be replaced dynamically based on a feature gate, a simple DSL like `dry-initializer` becomes insufficient. In such cases, we require a way to identify dependencies beyond their class constant. This is where `dry-container` comes into play. Its purpose is to provide identifying key names for registered objects.
Suppose we need to replace `ConfirmationEmailer` with a `NotificationService`. Using `dry-container`, we can dynamically choose our injected dependencies by identifying them with keys, rather than relying solely on their class constants.
Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.