Mike Morearty
07 Jan 2013

Questions about DHH’s view of Dependency Injection in Ruby

DHH’s Dependency Injection is not a virtue post is interesting. He makes a good point, that Ruby is fundamentally different in some ways from Java, therefore different rules may apply. But there are some aspects of his Time.now example that bothers me, and that I think might be kind of important. I’d be interested to know how people who have more experience with Ruby than I do would respond to these concerns.

If you are writing a test and you “override” the Time.now method, that might be fine if you are testing just one little method. But:

  1. This means you are overriding Time.now for any function that might be called farther down the call stack. Potentially error-prone.

    I get the sense the Rubyist’s response would be, “You are worrying about the wrong things, you’re worrying about things that are theoretically possible but are in practice unlikely to happen.” Is that right?

    For that matter, I see what he is doing as basically a Ruby version of DI, just not as good. He is saying, “Look, when you are coding in Ruby, when you see Time.now, you just need to know that that is not as hard-coded as it is in Java. It might have been redirected.” Okay, then basically that is DI, right? Except that it affects all callers of Time.now, not just the one you were intending to change.

  2. That specific example only applies to testing scenarios — not to DI in general. I guess testing is the main place where DI is useful, though. But that fact that the stub method is part of RSpec-Mocks implies that it is intended to be used for testing, not other things. Still, I find the DI model a useful one, because I don’t like hard-coded dependencies between components, it tends to lead to trouble in my experience.

  3. It breaks encapsulation. The only way to test the publish! function in his example is to look at its implementation. Again, maybe the Rubyist’s response is “You’re worrying about the wrong things”?

    Maybe I’m stuck in an old way of thinking — certainly I was a hard-core believer on static typing for a very long time. (And still am, to some degree — I still have not written anything of even medium size with dynamic typing, and although I think dynamic typing is great for small projects, I’m still skeptical about it for anything else.) But I don’t know, encapsulation has served me really well, and it is hard for me to imagine that this example is sufficient reason for abandoning it.

comments powered by Disqus