Hacker News new | past | comments | ask | show | jobs | submit login

Reading and re-reading the StackExchange answer with the most votes, I'm still not sure I get it. It SEEMS like he's saying:

[1] Hand-rolling a class around the "Gang of Four" singleton pattern is bad (i.e. tightly coupled, etc).

[2] Grabbing a singleton reference from Spring, CDI, Guice, or some other dependency injection framework is awesome (i.e. easier to use inheritance, abstract out some interfaces, inject mock objects into your unit tests, etc).

Am I missing something here, or is this entire discussion really no more complex than that (once you scrape away the enterprise-babble)? It's been almost a decade since I last worked on a non-trivial project that wasn't using a dependency-injection framework anyway, so some of this may just be so obvious I haven't thought about it in awhile.




The top answer is basically saying:

1. The "Gang of Four" "Singleton" pattern, meaning stateful functionality that is statically available from anywhere, is broken. It hides dependencies and makes it impossible to uncouple the items for testing.

2. However, the idea of an application needing a single instance of an object, whether it be a configuration or renderer or what-have-you, is quite common.

3. Using "dependency injection" allows use of single instances, without the "Singleton" pattern. Which, to clarify, does not necessarily mean the more magical forms of dependency injection found in systems such as Spring, where you simply declare a variable and it is magically fulfilled later. It can also just be a parameter in the constructor of the dependent object.




Join us for AI Startup School this June 16-17 in San Francisco!

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

Search: