5 ms·
Singletons come to mind as being a better alternative in languages that can do that sort of thing.
by throwaway889900 5y ago
Singletons come to mind as being a better alternative in languages that can do that sort of thing.
- sagichmal 5y agoSingletons are globals, aren't they?
- dcow 5y agoKinda depends. Single instance things are usually globally referenced, but as long as you're referencing an instance and not a static thing they're not hard to convert to an "injected" dependency if you need to provide a test impl to some thing being tested. The real problem is static things that can't be swapped out because you're actually calling static methods on some class rather than sharing an instance and calling instance methods.
- Chris2048 5y agoI see your point, but aren't all those things architecture dependent i.e. dependent on the implementation of the prog-lang environment?
- dcow 5y agoYes.
- sagichmal 5y agoI understand "singleton" as "only one exists" and "it exists in the global scope". That is, if I create one instance of something in my `int main()` that's not enough for it to be a singleton. That's important, because there's more than one way to enter your program. Notably, tests don't flow through your main entrypoint.
- gpderetta 5y agoSingleton is just a fancy name for a global.
- throwaway889900 5y agoAh, but they come with the benefit that you are forced to only ever make one. A global doesn't prevent you from doing that, so singletons are ever so slightly better.
- Chris2048 5y agoYes, but hence a global "but .. better managed" :-)
- w0mbat 5y agoPeople also bash singletons, so you can't really win. You can get issues with a singleton being accessed for the first time from multiple threads at once, for example, so you end up with more than one instance being created or a situation where one thread triggers the creation and another accesses before it has been fully initialized, depending on the code.
- throwaway889900 5y agoIf you expect that sort of thing to occur, then your get method should be synchronized to prevent it.
- dcow 5y agoThese days in both Java and Swift you can just lazily reference a static class field/property set to an instance of the singleton (in java the field must be on a dedicated private class) and the Runtime will lazily initialize it exactly once in a thread-safe manner the first time it is referenced.
- w0mbat 5y agoThat's only the tip of the iceberg I'm afraid. If the singleton has methods that perform actual work asynchronously and different threads are hammering on it, all kinds of issues come up. Of course a seasoned developer is going to acticipate this and write the needed infrastructure, but a newbie is not. It can be better if different threads have their own worker objects with their own state for example.
- deleted 5y ago[deleted]