by brundolf · 6y ago · 0 comments
For me and probably a lot of people here, the pattern fundamentally offends my sensibilities; mainly, but not exclusively, because it forces you to put everything into classes. I'd much rather pass plain functions when I need inversion of control, and use closures if I really need to "configure" some piece of code. I'd also prefer to import and pass down those functions explicitly, instead of having values magically resolve in some runtime context that lives outside of the "real language". I do acknowledge that languages like Java don't, or at least didn't for a long time, support these other language features and so may have had no choice but to use DI as a crutch. But I've also seen it used in languages that do have those features, like JavaScript.
On the other hand, I'm not sure I've used the pattern enough to critique it fairly. And obviously it's been used for decades at many very large and successful companies. So what I'd really like is to hear from someone who's experienced with both worlds about the advantages and disadvantages, assuming that both exist.
I think it’s an important point to clarify because DI on its own absolutely does not live outside of the real language and while it may be much more common to use classes than functions it’s not necessary.
I agree with your feelings in relation to DI containers however.
In Java functions/closures and objects/classes are the same thing. You have the best of both worlds. You can for instance define a function that takes an argument a and a function b and pass it either a functional lambda or a class that implements said function:
static void doSomething(int a, Runnable b) {
if (a > 0) {
b.run();
}
}
doSomething(1, () -> System.out.println("hello"));
Runnable r = new SomeClassThatImplementsRunnable();
doSomething(0, r);And it has the power of locality over an IoC container.
That being said, please remember that a class and a closure are essentially the same thing with a different syntax.
I've long been in the pro DI camp and used to think that interfaces and brittle tests were unavoidable..
Only after i recently got into FP with f#, I've come to appreciate how i used to conflate good IoC design with DI usage.. I'm pretty sure that I'm not alone
As for ceremony and semantic load, I can't argue here, though I think following DI restricts some of the semantic load that comes with abstracting mainly through inheritance and through managing stateful dependencies.
Call me a weirdo, but I enjoy using Spring DI with Scala. It's quite easy to inject into a constructor like "class Foo(f: Int => String)" even if a little bit of "manual currying" is sometimes needed.
I've never tried it but I'm fairly certain that most C# IOC containers should allow you to resolve functions if you really wanted to go that route.