0

I have been reading Joshua Bloch's Effective Java book. In item #5, he seems to say not to use a singleton or static utility class to implement a class that depends on one or more underlying resources, and do not have the class create these resources directly, use dependency injection.

I would like some clarification on precisely what advice he is trying to give here. Should I not make a singleton or static utility class at all (and use just a class) when I have some variables that affect that class? Or I can use it, but just need to use dependency injection? Which of these strategies would be most consistent with Bloch's advice?

halfer
  • 19,824
  • 17
  • 99
  • 186
Leo4343
  • 9
  • 2
  • There may be some confusion here because Josh Bloch's Singleton is quite different from the more common Spring Bean Singleton. See https://stackoverflow.com/questions/2637864/ for details. Assuming you are in fact talking about Bloch's Singleton, how do you propose using it with Dependency Injection? – jaco0646 Jan 09 '21 at 15:15

1 Answers1

1

Joshua is talking about classes that are gateways to resources like databases, filesystems, or all kinds of network resources. They are hard to replace with alternative implementations. If you just use regular classes, potentially implementing an abstract interface, you can inject them wherever they are needed and replace them by injecting something else instead. The prime example of such alternative implementations are Mocks/Stubs/Fakes used in unit tests where you do not want to access the actual underlying resources. Other examples:

  • replace reading from JSON files by reading from YAML files
  • replace reading/writing from/to one database system with something that reads/writes from/to another database system
  • replace routing via google maps by reading from here.com
  • etc.
EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
  • Yes, I understand this. But he had 3 examples (2 bad and 1 good). The first one is singleton. The second one is utilities class and there are both without dependence injection. The last example he gave was with dependency injection. It was just a class. So can I use dependency injection in singleton. Or it is not best practice and I should use dependency only in plain classes? (Can add his code if it is needed) – Leo4343 Jan 09 '21 at 12:44
  • Are you talking about injecting something into a singleton? Why would you do that? Just inject the dependency where you would use the singleton otherwise. BTW: I have very rarely seen a valid use of Singletons. You are almost always better off without them. – EricSchaefer Jan 09 '21 at 12:47