Did Joshua Bloch say not to use singleton with underlying resources?

324 Views Asked by At

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?

1

There are 1 best solutions below

2
EricSchaefer On

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.