by jmartinpetersen · 5y ago · 0 comments
I don't get blogs like these. This story has been told a million times with more or less the same content and structure.
There might be significant tradeoffs with singletons, but I wouldn't go as far as claiming they are an anti-pattern. Far from it. Managing and sharing a single instance across the whole application is a critical part of other basic software architecture constructs like dependency injection or even handing app settings.
I agree that it is an antipattern.
Not quite, you're confusing a particular way a singleton is implemented with the whole purpose of a singleton and why there's a need to restrict a class to have a single instance to begin with.
To illustrate your misconception, you can instantiate a regular class as a global variable and specify that no other instance is allowed in a project in the project's coding standards to enforce this at the code review level, and you still have a singleton.
The whole point of a singleton is that only one instance of a class is used across the system, regardless of whether this is enforced by any technice or not.
Don't confuse a specific implementation with the purpose, and requiring/expectinv only one instance of a class to be available is obviously not an anti-pattern.
I'll disagree. There are very few situations where restricting class instantiation to one object both solves a problem and doesn't cause unneeded headaches.
Almost always a boring global with careful access control is better. It provides a single object just as well without limiting options for future software engineering needs: testing, adding construction parameters, migration, gradual deprecation, etc.
As to legitimate uses, anything with system scope can't be controlled within a process. And there are few things that inherently couldn't be instantiated twice that aren't better managed by the OS.
Have you actually read the definition(s) of the singleton pattern? E.g. Wikipedia: "In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance." (https://en.wikipedia.org/wiki/Singleton_pattern)
And it's the same in most other definitions.
Also, make sure to read the criticism on the Wikipedia page - I think the criticism there is enough to classify it as an antipattern, because again, it's not about just having one instance of a type/class.
Yes, but things like this need to be repeated every few years to show it to a new generation of coders.
30-40 some year olds of today have probably been exposed to the original design patterns book already, but a younger generation grew up and worked with different tech, e.g. ruby / python / php, where these design patterns were reinvented.
I mean Ruby on Rails and some PHP frameworks from the 2000's / 2010's reinvented the MVC framework / design pattern, I had never heard of it before until these came back with it, but it's a pattern from the 70's apparently.