Hacker News new | ask | show | jobs
by knuthsat 1733 days ago
My take on this is that just injecting stuff in a constructor is an antipattern. Why not pass the data through methods instead of accessing it through a singleton in a constructor?

I understand the need for DI, sometimes the order of instantiation is necessary but for everything else I get lost in the DI constructor injection stuff.

1 comments

There’s typically a separation between “services” and “data” in this style of app. Data is typically a request or some result obtained from another service such as the database. A service can have a lifetime distinct from the data, such as a database service that uses a connection pool, which is scoped to the lifetime of the application.

In a functional language you could use a reader or environment monad to abstract the dependencies, but you don’t have that ability in a language like Java (and it’s not worth torturing the language to do it because it’s not idiomatic). So DI in Java ends up constructor-injecting service dependencies and using the method parameters to declare data dependencies.

Edit: another benefit of DI is that it allows for multiple lifetime scopes beyond application and method call. Spring has request and transaction scopes, for instance. Managing all that in Java without DI is a nightmare.