From: Avdi Grimm Date: 2008-04-10T06:51:41+09:00 Subject: Re: dependency injection with Needle gem On Wed, Apr 9, 2008 at 4:44 PM, Daniel Berger wrote: > DI has no place in Ruby. So says Jamis Buck himself: > > http://weblog.jamisbuck.org/2007/7/29/net-ssh-revisited > > "I've since learned my lesson and have come to understand that > although DI is a nifty technique that works well in some environments, > it is wholly unnecessary in Ruby. Ruby sports an agility that Java > will never know, and can get by without such crutches." There's a difference between dependency injection the pattern, and dependency-injection tools/frameworks. It's still a good idea to write classes that have their collaborators passed in, rather than finding or creating them internally. One of my favorite examples: # 1. Not so great class Whatsit def initialize @timestamp = Time.now end end # 2. better class Whatsit def initialize(clock=Time) @timestamp = clock.now end end #2 is better because it's decoupled from the nondeterministic system clock, and thus easier to test. Sure, with ruby Mock Object libraries you can do things like: Time.stub!(:now).and_return("TIMESTAMP") ...but this runs the risk of breaking unrelated code that also happens to be called in the test. And no, that's not a theoretical risk; I've had real tests fail because I needed to deterministically test time-based code and some other code (like, say, RSpec itself) depended on Time.now. DI frameworks may be overkill in Ruby, but DI is still a good way of breaking up your dependencies and keeping things decoupled. -- Avdi Home: http://avdi.org Developer Blog: http://avdi.org/devblog/ Twitter: http://twitter.com/avdi Journal: http://avdi.livejournal.com