Hacker News new | ask | show | jobs
by l_t 2310 days ago
I like dependency injection even when I'm not writing tests (which I usually skip for side-projects.)

I find it natural and convenient to think about "What dependencies on other parts of the system does this code have?" Expressing those dependencies explicitly feels like it reduces complexity, not adds it.

But, I'm not talking about pulling in a big fancy DI framework, just making dependencies explicit in your function/class parameters.

I will say that DI is sometimes used as a tool in overly-abstracted systems. An example that comes to mind is the ASP.NET MVC framework -- with DI and inheritance, literally any behavior can be overridden in fairly opaque ways. Trying to suss out the concrete behavior details is like swimming in quicksand. (Or it used to be that way, haven't touched ASP.NET in a while.)

As an aside -- I'm curious about your programming language of choice. I think DI is a lot more useful in some PLs than others. For example, I find JS code often uses imports to create complex graphs of implicit dependencies, and DI can help tame that complexity. But for other PLs like Python or Clojure, I basically don't use DI at all.

1 comments

Javascript doesn't "need" dependency injection because modules are objects, and you can mock those directly by replacing what they reference to. Very similar story in python. You could say people do DI in these dynamic languages without calling it DI.

Now Java and C# are different because they are compiled. You need a DI tool to do dynamic dispatch if you want to mock.

It's all aspects of the same thing.

You can't inject a nuclear reactor into a burrito in any language untyped or not because it will lead to an error.

The only difference is python/js the error will happen at runtime while in C$/java the error happens at compile time.

The main difference is the type. In typed languages you need describe am interface or a class of types if you want to do mocking or dynamic dispatch while in dynamic languages you don't need to explicitly define this as a type, the definition exists in how you use the object that is passed in.

Either way DI, however universal, in any language is bad practice.