Inject your dependencies

Steve Robinson
Spritle Software
Published in
2 min readSep 14, 2016

Dependency Injection (DI) is not a very well received idea in the Ruby world. But once you understand what its all about, its not at as scary as many people consider it to be.

Let me explain it to you using a very simple example. Take a look at this method from my application —

def setup
Subscriptions::Manage.new(subscription).setup(Plan.base_plan)
end

This allows me to create subscriptions for our user accounts using the plan obtained from Plan.base_plan.

Everything was fine until one day I wanted to use this method to setup some users with a different plan via the rails console. Boom! Turned out I would not be able to do this without making changes to the method.

What if I had written the method like this —

def setup plan=Plan.base_plan
Subscriptions::Manage.new(subscription).setup plan
end

Now, I could simply call setup(my_new_plan), whenever I want to use a plan other than the base_plan.

This, my friend, is nothing but Dependency Injection. The plan was a dependency of the setup method and we’ve simple injected it through the method’s arguments.

You can also imagine how easy it would be to unit test the DI version of the method compared to the former one.

Dependency Injection lets you reduce coupling in your code and keeps your code flexible reducing cost of future changes — which is one of the primary goals of software design.

DI is a way of achieving Inversion of Control which is one of the SOLID design principles. If you’re new to SOLID, I highly recommend listening to Sandi Metz’s classic talk on the topic at GORUCO 2009 —

And if you’re interesting in Object Oriented Design and learn more concepts like these, I highly recommend diving into her famous book — Practical Object Oriented Design in Ruby.

--

--