Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

There are lots of reasons why static references are undesirable, but some of the more serious are:

* Static dependencies make testing harder, no question about it. This is mediated in dynamic languages like Ruby by mocking statics. While you can actually do this in Java with Powermock, avoiding mocks entirely is even better. If you can't use a real object, use a fake that implements the relevant interface.

* Statics mean singleton, and that invariant often changes as a product matures. It's very easy to go from "the database" to "a database", and when you have 500 places getting "the database" it's very hard to make that evolution.

* Statics make it very hard to maintain module boundaries, because every static is its own exported interface. In a long-running project, binding tends to get tighter and tighter as every module reaches out for the statics of other modules.

Sure, folks can write bad code with DI systems too. And I'm no fan of Spring - not because of the DI, which is fine, but because of the need to wrap everything else in the universe and now you have to understand both how the underlying thing works and the way Spring changes it. But something like Guice or Dagger is just the right amount of glue to hold a system together, without getting in your way.



Just a note: I overloaded (excuse the pun) the word "static": I didn't mean the "static" keyword, but "statically compiled/typed". So it doesn't mean singletons, just that you pass dependencies as explicit arguments to constructors and functions.


I do not understand what distinction you're making. In the world of DI, you still have typed constructors and factory methods. It's not like Guice turns Java into Ruby. The only difference is that you don't have to chain together constructor boilerplate - in fact, the static types determine the injections.

Do you object to passing interfaces vs concrete types? That is a wholly orthogonal concern; you make the choice to extract interfaces with or without DI.

Maybe you have an example?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: