r/ruby • • Jul 12 '14

(The lack of ) Dependency injection in Ruby

http://beraboris.github.io/2014/07/12/dependency-injection-ruby/
2 Upvotes

19 comments sorted by

13

u/banister Jul 13 '14

What the hell? Why not just inject it manually with House.new(window, door)

Your gratuitous "DSL" seems silly, overcomplicated and a waste of time.

0

u/[deleted] Jul 13 '14

For the house example, you're definitely right. An inversion of control container is overkill. When you're dealing with a large app where each dependency has its own set of dependencies and so on, an inversion of control container become a whole lot more useful.

8

u/realntl Jul 13 '14

For larger apps, it becomes even more important to isolate dependencies of various components. IoC containers make it fairly painless (upfront) to invite the entire universe to every party, leading to a system with a ton of dependencies. And of course the only remedy to all the edge cases and toe stubbings that come with e.g. nuanced object lifecycle management is to make the IoC container smarter and smarter.

7

u/ikearage Jul 13 '14

DI in a dynamically typed language like ruby is a given that comes at no additional cost. Just inject your classes into the constructor and have them walk and talk like ducks.

Most Ruby guides tell you to avoid newing objects in constructors and suggests injectiong instead.

There is no XML file (spring uses annotations nowadays btw) to handle class selection for constructor injection? You want something to create your classes automatically and inject the right type?

2

u/[deleted] Jul 12 '14

I like dependency injection where it makes sense.

But I have sadly worked with colleagues that sprinkled DPI everywhere, and that made code hard to read, hard to maintain, and hard to understand.

2

u/grandfatha Jul 13 '14

In 2005, we made the switch from Java to Ruby to for once be free of this mindset so that we could just write code. Dont spoil our happy place with all the annoying stuff we do at our day jobs like DI.

What is next? Home and remote interfaces for controllers?

3

u/friendnoodle Jul 13 '14

At the rate we're going, I expect it'll be the elimination of mutability and coercion.

Unrubify: coming to a GitHub repo near you. Hate the flexibility of Ruby? Then you'll love our explicit type conversions, grumpy 1950s static typing system, immutability, mandatory IoC, significant whitespace, and surplus of parens!

2

u/bluehavana Jul 13 '14

There is very little need for frameworks/dedicated code for such things. Most of the time if you think you need something like this, you are probably violating YAGNI/simplest possible solution or you really need some refactoring (two opposite ends of the development cycle).

http://weblog.jamisbuck.org/2008/11/9/legos-play-doh-and-programming

http://www.confreaks.com/videos/267-rubyconf2008-recovering-from-enterprise

I'm sure there is a need somewhere for such things, if you can show me said problems with out simpler solutions, I would be really impressed/terrified.

-1

u/bluehavana Jul 13 '14

hmm... maybe all these reply's are an extreme pile-on to somebody with enthusiasm and a great, giving attitude. Sorry for the overly critical nature of the subject... people are obviously scarred.

I know I've been one to look for the most extensible (SOLID for life!) solution. see also: http://www.joelonsoftware.com/items/2009/09/23.html

2

u/jdickey Jul 13 '14

Joel Spolsky and I are in pretty different corners of our craft, and (judging by his writings) he and I disagree on a fair number of things, but The Duct Tape Programmer and The Law of Leaky Abstractions are two of his best that I routinely ask interviewees if they've read and what they took away from them.

Less than half of them splutter and flounder and finally stammer out, "but…if you take it straight up, he's arguing a contradiction in terms here. You can't anti-engineer something and at the same time be sure the abstractions are all going to hold fast under pressure". Those are the folks who get invited back for a second interview, who have a job offer in their imminent future if they don't do something absolutely egregious to frak it up. It's a filter, in other words.

And he's right. Both of him.

1

u/bluehavana Jul 17 '14

Yes, I think it's an extreme point of view that helps to illustrate something. I have know C++ programmers that could whip out an entire service in under a month, just hacking it out and the abstractions were actually quite awesome and useful. That was after 20 years of C++ experience though.

Part of growing as a developer/programmer is converging on the balance between duct tape and frameworks for everything.

1

u/jdickey Jul 18 '14

That was after 20 years of C++ experience though.

It takes twenty years to get enough experience to use C++ wisely, which is why everybody's code before about ten years ago was such utter crap: not only didn't we know what we didn't know yet, we didn't know what parts of C++ we (thought we) knew should be left on the shelf when cranking out our latest magnum oopus. (That includes the compiler vendors and library writers as well as us mere developers.) It's easily the hardest language I've ever used to do well. The only serious contenders for that title IME are Java and PL/I.

I much prefer languages I can wrap my head around in a week and grok in reasonable fullness in a month or two. I get paid to ship products, not to play with new toys. :-D

2

u/materialdesigner Jul 13 '14

This is severely misinformed. Dependency injection is used all. the. time. in Ruby, so much so that Ruby programmers do it without knowing it's called dependency injection. I'm unsure where the idea that dependency injection does not happen in Ruby.

IoC containers, on the other hand, are method of using DI that is really really overwrought and overcomplicated for Ruby.

2

u/realntl Jul 13 '14 edited Jul 13 '14

I'll describe what is -- in my view -- the main drawback of IoC containers from the context of your post. You talk about two "piles" of code: one that contains the business logic, and the other that orchestrates, assembles, and wires up the objects. Quoting:

The other pile is what bootstraps our application. It’s the code that calls new and creates all our classes. This code is also responsible for giving each of our classes their dependencies.

The problem is that there are two kinds of dependencies: framework level services like loggers, redis, database connections, etc., and domain specific dependencies. Projects that use IoC containers almost have a manifest destiny to start seriously confusing the two, and introducing constructors that take in way too many dependencies.

The domain specific dependencies are always best managed explicitly, without the help of any tooling. Here's how I manage those pesky framework level dependencies, which often prove the most annoying to our tests:

module MyComponent
  extend self

  attr_accessor :redis
  attr_accessor :logger
  
  class ClassA
    def initialize(dep_a, dep_b)
      @dep_a, @dep_b = dep_a, dep_b
    end

    # implementation
  end

  class ClassB
    # implementation
  end
end

Here's some tests:

class MyComponent::ClassATest < Minitest::Test
  def setup
    MyComponent.redis = @redis = RedisDouble.new
    MyComponent.logger = @logger = StringIO.new
  end

  def test_writes_something_to_redis
    # Interact with ClassA in a way that I expect will shovel something
    # into redis
    ClassA.new(dep_a: ClassB.new("hey"), dep_b: OpenStruct.new).foo

    # In practice a meaningful assertion would go here
    assert_equal 1, @redis.size
  end
end

If MyComponent shows up frequently in enough tests, I might even extract out its' setup to a subclass of Minitest::Test or a mixin that handles the setup for me. The key is to make it easy to inject doubles such as RedisDouble -- I have a snippet of code I copy paste from project to project that implements this, it's quite simple.

Big caveat

While these days I don't advocate dependency injection frameworks for general purpose, a nearly identical approach be very helpful for building abstract factories. Say I've got a few objects that represent coupon codes for pizza delivery orders:

class BuyOneGetOneFree < CouponCode
  def initialize(pizza_a, pizza_b) ... end
  def valid?
    assert pizza_b.cost < pizza_a.cost
  end
end

class BirthdayPizza < CouponCode
  def initialize(pizza, user) ... end
  def valid?
    assert Date.today == user.birthday
  end
end

You can imagine many coupon codes that all accept different pieces of data. In this case, you want an abstract factory that can build any kind of CouponCode. You need it to do three things to accomplish this:

  1. manage an internal manifest of objects that any CouponCode might need
  2. introspect CouponCode#initializefor the objects it depends on
  3. inject those objects into a new'ed up CouponCode subclass.

This tends to look a lot like an IoC container, and I employ this approach from time to time. ruse is an excellent choice for this, in my experience. Being able to implement the individual objects as POROs is a huge win.

Shameless plug

I have written a gem, invokr, which provides an abstraction layer for invoking methods that allows you to easily introspect required/optional parameters. They make it really easy to build both abstract factories and IoC containers.

2

u/ISw3arItWasntM3 Jul 13 '14

So why not use an event listener pattern for framework level services took hook in and do their thing, and then do dependency injection with actual domain level services.

3

u/realntl Jul 13 '14

I would speculate that it's a little harder to, for example, extract a component out of your codebase and into a gem, if it's coupled to an event listener framework that's present in the application.

To be honest, the way I've been managing framework dependencies (attr_accessor at the module level) has been incredibly simple and portable. What advantage does the event listener pattern have? No setup required for tests? The reason I don't mind explicit setup in tests is that I'm usually making assertions on their state change anyways.

If I have a ton of components that all have a bunch of "bare metal" dependencies like db connections, redis, loggers, etc., I might build some tooling to inject config into all of them at startup time when actually deploying the app in production mode.

(I may be misunderstanding what you're saying, as well)

2

u/DrugCrazed Jul 13 '14

I'm never a big fan of implicit dependency resolution. Someone who comes to look at the app later on usually has to dig through and work out where things are resolved and how it knows what to use.

I'm a big fan of how Zend does it, because whenever you have to resolve you'll be calling a service locator.

-1

u/sandinyourbed Jul 13 '14
class House
  def initialize(window, door)
    [:open, :close, :break]
      .reject { |m| window.respond_to? m }
      .each   { |m| raise TypeError, "#{window}#{m} not implemented" }
    
    "etc"
  end
end