3 ms·
Googe Guice's documentation has a nice explanation of how to scope objects (from http://code.google.com/p/google-guice/wiki/Scopes http://code.google.com/p/goog
by jmitcheson 15y ago
Googe Guice's documentation has a nice explanation of how to scope objects (from http://code.google.com/p/google-guice/wiki/Scopes http://code.google.com/p/google-guice/wiki/Scopes). How they word it is specific to Guice but the underlying points are valid for any Java application
"Choosing a scope
If the object is stateful, the scoping should be obvious. Per-application is @Singleton, per-request is @RequestScoped, etc. If the object is stateless and inexpensive to create, scoping is unnecessary. Leave the binding unscoped and Guice will create new instances as they're required.
Singletons are popular in Java applications but they don't provide much value, especially when dependency injection is involved. Although singletons save object creation (and later garbage collection), getting a handle to the single instance requires synchronization. Singletons are most useful for:
* stateful objects, such as configuration or counters
* objects that are expensive to construct or lookup
* objects that tie up resources, such as a database connection pool."
I have to admit that when I first started coding Java/Guice I had 'singleton addiction'. Luckily with Guice, as someone else mentioned, it's just matter of deleting the annotation on a class to change your mind about that.
Anyway, if you use Guice and dependency inject your singleton classes, then the issue of being hard to test and disguising dependencies goes away, doesn't it?
- misterbee 15y agoIf you use Guice you aren't using a singleton anymore. Guice is creating an instance and passing it to multiple classes as a dependency. This is different from any class just referencing a Singleton by importing it statically. It's a slightly subtle distinction, and you still have the risks associated with non-local mutable objects, but at least you can track (using the Annotation API) which classes are using the shared state; it's better than letting any line of code anywhere in the middle of any method sneakily and suddenly grab access to shared state.