Quantcast
Viewing all articles
Browse latest Browse all 8

Answer by JimmyJames for Is utilizing a singleton for a cache an antipattern?

I feel like the hate for the Singleton pattern is a little over-the-top. Yes, it can introduce some challenges, but it can also be a very simple solution in narrow circumstances. I think some of the invalid reasons for its bad name are:

  • Overwrought, unecessary, and broken implementations such as double-checked locking
  • Overuse. When Design Patterns were really hot, a lot of people learned exactly one pattern (Singleton) and used it all over the place where it wasn't appropriate at all.
  • Misunderstanding. Singleton, as typically implemented, is a simplification of the GoF pattern. E.g., the pattern shows a polymorphic implementation as an example.

That said, there are real issues. The main issue is testing. The standard Singleton is not easily replaceable with mocks or fakes in languages like Java.

The other primary issue is that if your assumption that there will never need to be more than one instance is wrong, or is no longer true in a future version, reworking the code to eliminate or enhance it can be challenging. Some of this can be mitigated by adding a (perhaps optional) parameter to your getInstance method and making it a 'multiton'.

My personal take is that the larger and more complex the application, the more problematic the approach becomes, and you should be using DI (with or without a framework.) If your application is relatively small and focused, introducing DI can be overkill. As long as you can accept the potential cost of reworking the code and your testing needs are met, I don't think it's design kryptonite that it's usually made out to be.


Viewing all articles
Browse latest Browse all 8

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>