Comments:"metablog: Dependency Injection is a Virtue"
URL:http://blog.metaobject.com/2013/01/dependency-injection-is-virtue.html
Having hard-coded class-names like in the example Time.now
is effectively the same as communicating
via global variables. DHH's suggestion of stubbing out the Time class's now
is selling us mutable
global variables as the solution to global variables. Or more precisely: passing an argument to a method
by modifying a global variable that the method reads out and restoring the state of the global variable afterward.
If that's "better", I don't really want to see "worse", and not wanting that sort of thing has nothing to do with being a Java drone limited by the language. And my experience with time-dependent systems tells me that you really want to pass the time into such a system generally, not just for unit testing.
Of course, having n-levels of AbstractFactoryFactory
indirection could actually be argued
as being worse, as Tim convincingly does, but that's one implementation of DI that's hobbled by Java's limitations. For a DI solution
that's actually simple and elegant, check out Newspeak's module system (PDF): there is no global namespace, modules are parametrized and
all names dynamically resolved.
If you want synthetic time for a module, just instantiate that module with your own Time class.