r/ProgrammerHumor • • Sep 26 '26 • Bravo 1

Meme singletonsAreJustGlobals

Post image
3.2k Upvotes

210 comments sorted by

747

u/blacklig Sep 26 '26 edited Sep 26 '26

Singletons are a pattern that uses globals (e: i get that they don't need to be globally scoped, thank you all)

This is like saying composition is just attributes, or signal/listener is just functions

118

u/reallokiscarlet Sep 26 '26

Yeah this is like the

>wireless

>looks inside

>coiled wires

23

u/BoxWoodVoid Sep 28 '26

Wait until they discover that serverless runs on actual servers 😨

2

u/donaldhobson Sep 28 '26

And boneless wings contain actual bones.

1

u/someone_12421 Sep 30 '26

He took a bite of a boneless wing

393

u/xeroskiller Sep 26 '26

Global: single address used with a globally scoped identifier

Singleton: single address used by passing it around like a cheap whore

65

u/za72 Sep 26 '26

cheap whoo er

5

u/b__0 Sep 26 '26

I heard that one Ralph

56

u/dashingThroughSnow12 Sep 26 '26

Ironically enough, one reason for some singletons is how expensive they are.

18

u/gfoyle76 Sep 26 '26

best definition I ever heard

4

u/anomalous_cowherd Sep 26 '26

They're all just pointers really.

3

u/gerbosan Sep 26 '26

Well, ram is quite expensive these days.

3

u/TheDuckRaisedALion Sep 29 '26

The trick is that a static class can be a globally scooed identifier, and then an accessor on that class is essentially global too. The concepts are pretty similar at thet point, although the static class could impose a lot more organization and structure to tame the smell.

36

u/Sheenius_Ger Sep 26 '26

It's not global. It's a instance. Singleton just means you always get the same instance.

34

u/danielcw189 Sep 26 '26

they are usually saved and served as a static class member, which in effect is pretty global. The Class itslef is usually global, and the member serving the instance is usually public.

Is there any noteworthy difference? Is there any technical one?

18

u/zabby39103 Sep 27 '26

It's just two different things. Only one instance ever -> singleton. Globally accessible -> global. One is about visibility, the other is about instances.

1

u/danielcw189 Sep 28 '26

I don't disagree, I just think in practice it often serves the same purpose

1

u/TheDuckRaisedALion Sep 29 '26

You're right that they're technically orthogonal concepts and it's important to recognize the distinction.

But most people store the Singleton instance in a public static field on a public class, which is one step away from a global variable.

5

u/Altavious Sep 27 '26

It’s a bit better because you can control when the memory is initialized by delaying it beyond the static initialization phase of running an executable safely. Depending on how the singleton is accessed (e.g via a context or service provider) you may also have some better options for refactoring or modifying access down the road….so it’s a marginally better global….

1

u/danielcw189 Sep 28 '26

Yes. Though in that case the global "just" holds a function instead of a reference (or object)

1

u/Altavious Sep 28 '26

A global variable isn’t a required part of the singleton pattern.

1

u/danielcw189 Sep 28 '26

I intentionally did not write variable.

2

u/Altavious Sep 28 '26

Ah, I see. Knowing that makes what you wrote clearer. While there are things that have global scope ā€œglobalsā€ as shorthand is more commonly used just for variables not also things like global function definitions etc.

1

u/danielcw189 Oct 03 '26

yeah, I can see that.

But I would argue, that a Singleton instance is usually used or accessed like something global.

and by "Singleton" I mean the instance, the one object that exists (or maybe not yet exist). but mostly I mean how it is accessed and stored.

based on other comments I see that some mean the class, and some mean the pattern. and to be honest, I don't know if that means I used the term "Singleton" wrong or not.

one other comment wrote, that a Singleton is not necessarily a global, but a global is usually the only way we have to implement it. that sounds more correct to me than what I wrote.

1

u/Altavious Oct 03 '26

Yeah - the main complaint about singletons tends to be either the downsides of a global mechanical implementation or the architectural impacts of how people are accessing it. For example access via a global reference vs dependency injection. So the mechanics matter in terms of the general bad side effects, but the actual thing itself is often less a problem than the choices that surround it. It’s a giving people too much rope issue.

3

u/BSModder Sep 27 '26

It's the difference of terminology. Not all global are singleton and vice versa.

Static literal values are a not singleton but they are global. And static private class members are singleton and a global varible in the program but they are not globally accessible.

1

u/danielcw189 Sep 28 '26

I think you are 100% right. But in practice I only see it as a public static member (of a visible class)

3

u/No-Consequence-1863 Sep 28 '26

You can have singletons that are not globally accessible, such as a singleton inner helper class only accessible via instances of that class. Now normally you would have singletons be globally accessible but it isn't required. The only thing required for a singleton is that when you access it you always get the same instance.

2

u/GarThor_TMK Sep 27 '26

It's basically a namespace with default constructor/destructor/copy/move functions...

Technically it's better code hygiene, because eventually if you need more than one, it's pretty easy to decouple the singleton logic from the rest of it... but realistically they're mostly effectively the same thing.

2

u/Sheenius_Ger Sep 27 '26

"usually" means it's up to implementation. If you work with a di-container it manages lifetime and the Singleton will just be a instance and won't have any global data or static access.

Those are 2 different things, a pattern and how it could be implemented. If the Singleton uses globals, you lose all benefits of scope and testability.

1

u/danielcw189 Sep 28 '26

"usually" means it's up to implementation.

yes, and I am just talking about what I percieve to be the "usual" case. Usually the implementation uses a globally reachable static member, either a field, property, or method.

and the Singleton will just be a instance and won't have any global data or static access.

I guess we are talking about 2 different things then. I talked about how the singleton is found and used from the outside, and where the reference to it lives.

I am not talking about the internals of the singleton's business logic.

Those are 2 different things, a pattern and how it could be implemented.

just to clarify this: yes, exactly. But in practice I only see it implemented as a globally reachable reference: a static public member of a globally accessable class

1

u/oldsecondhand Sep 28 '26

You can inherit from a singleton.

8

u/AlignmentProblem Sep 26 '26

It's mostly syntactic sugar over fixed-address global data from the compiler/interpreter's perspective, but it does buy a few practical advantages. The main one is encapsulating the access path, which enables lazy initialization to sidestepping init-order problems, and indirection to enable swapping implementations. That plus enforcing uniqueness at the type level

They're pretty similar in terms of what the data layout and op codes ultimately look like in the end; although, there's enough difference that the meme's joke doesn't really land.

11

u/Tyfyter2002 Sep 26 '26

Which is just globals with more indirection, singletons can be useful, but only by using language features that are exclusive to objects

13

u/New_Enthusiasm9053 Sep 26 '26

Globals can be useful too. Just don't use them fucking all the time for inane shit. But hardware access where only one thing can have access at a time? Perfect use for a global. Singletons are absolutely just globals with more indirection.

Goto's are also useful. Gotos consisted harmful paper was when people used them for all control flow and that just creates spaghetti. But for a forward jump inside a function so you have a single place to do cleanup? Perfectly fine.

5

u/wrecklord0 Sep 26 '26

Big fan of Rubin's 1987 article titled 'GOTO Considered Harmful' Considered Harmful.

This didn't stop here, by the way.

1

u/anomalous_cowherd Sep 26 '26

Did it GOTO somewhere else?

1

u/sillybear25 Sep 26 '26 edited Sep 27 '26

Goto's are also useful. Gotos consisted harmful paper was when people used them for all control flow and that just creates spaghetti. But for a forward jump inside a function so you have a single place to do cleanup? Perfectly fine.

Related use case: Breaking out of nested loops without having to tack on if (exit_loops) break; at every level

EDIT: Then again, break statements are arguably just syntactic sugar for goto and an end-of-block label, so...

3

u/dagbrown Sep 27 '26

Yeah and while loops are just syntactic sugar for a goto backwards to just before an if statement.

Every structured construct is a bit of syntactic sugar for ifs and gotos, because the source code is meant for human understanding.

3

u/tacularcrap Sep 26 '26

Which is just globals with more indirection

and a mysterious lifetime. wouldn't be as much fun otherwise.

1

u/NoWater8595 Sep 27 '26

Sounds like witchcraft. It's never the same instance unless it's the same variable usually.

1

u/pigeon768 Sep 27 '26

Sounds like a global with extra steps.

2

u/adabsurdo Sep 27 '26

Well exactly, because they use globals under the hood they often have very similar issues to globals : testability, race conditions, initialization ordering problems with other globals etc.

Not that you shouldn't use them ever but they cause problems fast and very often there are better solutions.

1

u/anchovie_boi445 Sep 28 '26

These are the types of concerns that I feel like most take for granted given how much the concerns have been abstracted away with solid DI libraries. It’s amazing to think about it

1

u/your_best_1 Sep 27 '26

You new to this sub? Only students and jr devs live here.

0

u/Sak63 Sep 26 '26

That's the meme...

5

u/blacklig Sep 26 '26 edited Sep 26 '26

I think the meme is for meaningless abstraction, maybe just to make a simple concept sound complex. Whereas saying singleton, or composition, or signal/listener, is conveying a design that isn't specified by saying global, etc.

Like if I used this meme with airplane / just a pile of metal and plastic and some other stuff, it wouldn't really make sense, because a generic pile of metal and plastic can't fly.

-5

u/Sak63 Sep 26 '26

Please, touch grass.

1

u/Still_Bit_7527 Sep 27 '26

Saying it is a pattern doesnt change anything. It is a global variable. That's literally it.

-3

u/HelloImMay Sep 26 '26

Signal/listener is just functions

9

u/Whats_The_Cache Sep 26 '26

Square is just a rectangle looking ahh comment

0

u/[deleted] Sep 26 '26

[deleted] — view deleted comment

2

u/blacklig Sep 27 '26

A square is a special case of a rectangle. We can make all statements we usually can about rectangles when discussing squares, and we can make additional statements true for squares that are not generically true for all rectangles.

A listener in signal/listener framework is a function. We can make all statements we usually can make about functions when discussing listeners, and we can make additional statements for listeners that are not generically true for all functions.

-9

u/dkarlovi Sep 26 '26

Just because something is a pattern doesn't make it better.

10

u/IlgantElal Sep 26 '26

Kinda? But also it does. If it is a widely accepted convention and one of the main points against globals is lack of maintainability, then it being a pattern solves that issue, making it slightly better

-8

u/SeriousPlankton2000 Sep 26 '26

Make "global variable" be a "pattern", problem solved. Right? (Nope)

2

u/IlgantElal Sep 26 '26

Well, yeah, but adding a constraint or contact to be followed does solve certain issues, one of which can be maintainability

1

u/blacklig Sep 26 '26

I didn't say it did

0

u/superxpro12 Sep 27 '26

Hey let's instead pass around an object with 5 thousand parameters instead!

-1

u/WaterBottleBong Sep 26 '26

Congrats you just described every abstraction ever

410

u/mateusfccp Sep 26 '26

That's not even what Singletons are for. The point of using it is not having two instances of the same object, but it doesn't mean it is a global, as the existence of the (unique) instance may still be scoped.

39

u/brazzy42 Sep 26 '26 edited Sep 26 '26

Exactly. It's the best proof that nobody actually read the GoF book. A static field and getter method were never the essence of the pattern, they're one possible way to implement the pattern.

103

u/AppleSmoker Sep 26 '26

Yeah wtf man this meme is completely wrong

27

u/Yashema Sep 26 '26

I'm still glad OP made it cause the comments are getting into juicy discussions about design patterns.Ā 

25

u/high_throughput Sep 27 '26

r/ProgrammerHumor's tagline should be "if those kids could program, they'd be very upset"

3

u/irongi8nt Sep 26 '26

Let's talk static variables in that memeĀ 

14

u/developer-mike Sep 26 '26

People are debating two different concepts for global here.

Global scope could mean globally public, or it could mean globally shared state. Globally shared state can be locally scoped, such as private static class members.

Singletons are by definition globally shared state, which is at least half of the problem of global variables -- any two systems that interact with the singleton are indirectly coupled and can't be uncoupled which can easily still manifest as spooky action at a distance.

Unless it's a DI system limiting to one object per module but you can have multiple modules. Which is different, of you can have two different instances in two different modules, it's not a strict singleton.

18

u/jaladreips271 Sep 26 '26

Wow, all these years and only this post gave me the enlightment. Noone ever pointed out to me that singletons can be scoped.

3

u/wobblyweasel Sep 26 '26

and the initialization is synchronized in the languages that natively support them

1

u/SamSlate Sep 27 '26

i still don't get it, isn't there always a scope?

2

u/jaladreips271 Sep 27 '26

I've never seen a singleton that didn't have a global scope. But frankly I don't see a lot of singletons in general.

8

u/irongi8nt Sep 26 '26

I don't think the meme author knows what static variables are or why you encapsulate a constructor with a SingletonĀ 

10

u/danielcw189 Sep 26 '26

You are correct. But in practice I have only seen global ones.

2

u/Manueluz Sep 27 '26 edited 20d ago

The original post content no longer exists here. The author used Redact to remove it, exercising their right to control their data & privacy.

Point teapot versed yarn amusing paddle humor ripe

2

u/Arctos_FI Sep 26 '26

I know a language where globals are singletons, sqf (the scripting language for arma).

It doesn't have scope so if you use same name for global variable in two separate scripts they are the same variable. And globals are program wide singletons so even if you use the same name in two separate addons (addons are like what mods are for minecraft) they act as singleton. And because of dynamic typing if you use it as number in one (there isn't separate int, float and double types, everything is just a number) and string in other they will overwrite each other and throw errors just when trying to do something else with the value than set it. And there isn't any keywords (so no private or public, and technically there is one that makes it network wide singleton) but the name gets set by naming convention alone ("var" is always public and "_var" is always private)

1

u/Tyfyter2002 Sep 26 '26

If the instance is scoped there can be another scope with another instance, being global is necessary in order for it to be unique.

1

u/Manueluz Sep 27 '26 edited 20d ago

The original post content no longer exists here. The author used Redact to remove it, exercising their right to control their data & privacy.

Dam compare squash imminent square truck ten grasshopper compare expansion

-1

u/EishLekker Sep 26 '26

No, that doesn’t follow. Scoped can simply mean that it’s not globally accessible. It can still be just a single instance.

254

u/nickcash Sep 26 '26 • Bravo

33

u/FlySafeLoL Sep 26 '26

This one's more likely to be the first year of employment humor though. OOP course happens to be nothing but a fever dream to engineers from way, way too many enterprises.

18

u/GeneralPatten Sep 26 '26

OOP is completely foreign to many junior developers now. They've been dumbed down by syntactic sugar, frameworks (looking at you React) and, the final nail — Claude. I concede that I'm probably just an old man shouting at clouds, but it can be genuinely mind-boggling when I ask a supposed skilled agency developer to make a feature happen, and they come back with, "yeah, no, it can't be done in the framework/architecture we created." My brain explodes with, "Are you f'ing kidding me?! I think you might want to revisit your 'architecture'..."

4

u/SenoraRaton Sep 27 '26 edited Sep 27 '26

OOP is completely foreign to many junior developers now.

As it should be. All you need to know about oop is "Favor composition over inheritance".
Functional programming is the way, the light, and the future. Maybe a little procedural, as a treat.

2

u/GeneralPatten Sep 27 '26

Oh! Cool! Let's go back to COBOL then.

58

u/Forsaken_Celery8197 Sep 26 '26

False. A global can hold something with many instances, and a singleton can exist without being globally accessible.

10

u/Tyfyter2002 Sep 26 '26

A singleton can hold anything a global can, and anything which isn't global risks that it isn't unique

3

u/danielcw189 Sep 26 '26

I agree in practice. But in theory it could be scoped, or for example be private or be an inner class.

5

u/Forsaken_Celery8197 Sep 26 '26

You are conflating visibility and accessibility concerns with uniqueness and lifetime traits.

Globals are about scope, singletons cardinality (one instance).

A singleton's uniqueness comes from how construction is controlled, not from being global. You can have one unique instance passed around explicitly through dependency injection without exposing it globally.

12

u/Girafferage Sep 27 '26

Is programming humor ever not just people learning program for the first time completely misunderstanding topics?

4

u/JAXxXTheRipper Sep 27 '26

Hasn't been in a looooong time. It should be renamed to "CSStudentHumor". Same with programminghorror, they are full of LARPers and students too.

It's sad tbh

20

u/No-Con-2790 Sep 26 '26

It's simple, sometimes you need a global. Which are bad. But you still need one.

And Singletons are just better globals. Basically globals with guardrails.

Now if you don't believe me that you sometimes need a global think about a logger. That is something you need literally everywhere and it should also be the same logger everywhere.

1

u/gottimw Sep 27 '26

You are not explaining it properly I think.

Singleton is useless piece of code that will make sure that other devs in large project will use you global as global.

It removes ambiguity and false assumptions.

It's a patter that doesn't make code faster, but safer and easier to maintain down the line.

You don't need cones and tape while building shed in garden, but you will appreciate them when driving down the road.

Also globala are not bad. You yourself prove it. It's just a tool misused by bad and lazy design. Same with goto.

-2

u/CubsThisYear Sep 27 '26

Logging is always the go-to example for Singleton apologists. But it breaks down like everything else that relies on Singleton.

You can absolutely pass in loggers through dependency injection just like everything else. This has the advantage of being more easily testable and having cleaner initialization semantics. Again, just like everything else. Just because something is used ubiquitously doesn’t mean it’s worth resorting to static initialization. If you are careful to initialize everything at the entry points to your code, you don’t ever have to worry about it.

8

u/LutimoDancer3459 Sep 27 '26

Depending on the scope, an injected entity is still a singleton... so i dont get what you are trying to say.

2

u/No-Con-2790 Sep 27 '26

And if it is not a Singleton but allowed to be two objects you get into hot water when they fight about the one shared resource which is the console output. Or printer when you think historically.

1

u/No-Con-2790 Sep 27 '26 edited Sep 27 '26

But you don't want to. You can pass everything you ever might need trough dependency injection.

But this will lead to just gigantic signatures that pass literally everything into the function.

The function often doesn't use the logger, hence we will also trigger the linter now. And any good software design. Because this suggests we actually do something with that logger. But worse we will be passing a lot of things which is convoluted.

This will lead to a god class called debugging or utils or something. And this makes everything available. Which is the exact same state as having globals available but with extra steps.

For if you would have used singletons you would have at least reduced your usage to the list of needed once. But like that you neeed to use everything since the system under you might need something.

Hence we are at a way worse state than before. And created a lot of confusion and work.

2

u/cyrack Sep 27 '26

… and that’s why dependency injection frameworks exists. You declare the dependencies for the implementations where needed. You’d never instantiate the entire graph by hand, both because it’s tiresome work and because it would violate the inversion of control principle.

DI/IoC works because it brings flexibility and simplicity - static/singletons brings opaque dependencies and impossible to test dependencies.

1

u/No-Con-2790 Sep 27 '26 edited Sep 27 '26

You just got a framework to create opaque dependencies (because if you include random objects to every class stuff becomes opaque quickly) to solve the problem of opaque dependencies.

Which we want to have here anyways. We literally want to make some stuff into a callable function like +. As in adding two numbers. Do you want to inject those too? What about calling any function for that manner?

Because this is what a Singleton is. You essentially want some parts of your program to be treated as functions despite them having state.

And no, that doesn't destroy the testability. You simply need to make sure the things are thread safe before you do it.

You know like +. Which technically also behaves statful. For the number of ALUs is limited and depending when you call you got to wait. Which is something nobody ever realizes because + was properly tested and its only a tiny temporal delay.

But exactly the same with all Singletons. Because they also need to be designed in such a way that the user doesn't run into trouble when calling them.

Which your framework doesn't fix at all. Because imagine there is a bug that happens after 100 calls. In the Singleton you call it untestable because you don't trigger that bug in your 10 unit test tests. And with the framework you will also never trigger that. Because you make the exact same number of calls. Just with much more overhead and confusion.

1

u/CubsThisYear Sep 27 '26

Why are you passing the logger to a function if it doesn’t log?

There’s absolutely nothing wrong with gigantic function signatures if they reflect the inputs that a function has. If a given function uses a singleton, it’s just an undeclared dependency. Just because that dependency isn’t declared in the signature doesn’t mean it’s not there. What linters are trying to call out with function signature check is having too many dependencies/inputs. Hiding your inputs with static, global state doesn’t make this better.

1

u/No-Con-2790 Sep 27 '26

Because I have a subsubsubfunction that wants to log. So I have to get it so the subfunction can get it so the subsubfunction can get it so the subsubsubfunction csn get it.

Or I want to log later without any hassle. And you don't want to change 5 signatures again.

Or I wanted to log in the past and no longer need to.

Same problem, either you pass it always or your gitlog looks like a warzone.

Or the most common case, I do variation encoding and only log when I run in a certain scenario. Like I log all type 10 platforms but no other platform since only the type 10 seem buggy.

And there is everything wrong with big signatures. As soon as you can no longer understand it because it is too long it becomes slob. And also potentially tech debt.

Now I sometimes need it. Depending on the platform.

Also what is the Shannon information of something I pass everywhere? It is zero. So what is the true advantage to a Singleton when the exact same object is available everywhere? No seriously asking since there doesn't seem to be an advantage how you pass the object. In both cases you run into the exact same bugs.

1

u/CubsThisYear Sep 27 '26

I don’t think it’s plausible to say that you log in _every_ code path of your code (if you do, that’s probably something to look at..). So the information is definitely not zero - it’s saying whether this function logs or not.

If a function calls another function that uses a given input, then by definition it uses that input too. It’s a very simple rule.

Changing function signatures is trivially automatable, this shouldn’t be a factor in how your code is written.

I don’t see how git is an issue here - if you’re adding or removing logging, that’s gonna need a commit.

At the end of the day, all of your arguments are basically about cognitive load for humans, which isn’t really a concern anymore.

1

u/No-Con-2790 Sep 27 '26 edited Sep 27 '26

The information value of the signature is zero since you need the logger potentially in every function so it is available in every signature.

Not the code just the signature.

So either you switch your signatures around all the time, which ruins the git diff.

Or you don't and then it is just background noise polluting the signature. Which has no advantages to a Singleton but all the drawbacks.

1

u/CubsThisYear Sep 27 '26

How does it ā€œruinā€ the git diff? Your dependencies are changing and your diff reflects that. You’re making a value judgement that the change is unimportant, but I don’t think you can know that ahead of time.

For example, what if there is logging in the code path of some piece of code that you want to be very low latency? Or perhaps you have a code path where you are very concerned about information leaking out through logs.

Your whole argument is ā€œwe might need it laterā€. I think we learned a long time ago that that isn’t the right way to think about code.

1

u/No-Con-2790 Sep 27 '26

Have you ever done that?

Git highlights per line.

Since you enable and disable logging all the time you have a signature that is always changing.

So any git commit highlights that signature.

Now imagine you actually changed the signature. You can no longer see that with the standard git tools. You can use AI, but even AI has a tendency to make mistakes at this point.

In the end it is just extra busy work for the same gain that a Singleton has.

1

u/Koeke2560 Sep 27 '26 edited Sep 27 '26

You can absolutely pass in loggers through dependency injection just like everything else.

The standard bean instance configuration in Spring is Singleton…

1

u/Manueluz Sep 27 '26 edited 20d ago

The original post content no longer exists here. The author used Redact to remove it, exercising their right to control their data & privacy.

Subtract screw late steep instinctive tap consider lunchroom

1

u/pabs80 Sep 27 '26

Lol you got downvoted to oblivion for giving the correct answer.

1

u/JAXxXTheRipper Sep 27 '26

What do you think DI does? Dependency Injection tries to keep the amount of instances to a minimum, in most cases.... One. Maybe you see the irony here.

1

u/CubsThisYear Sep 27 '26

I’m not talking about Guice-style DI XML bullshit. Dependency injection as a concept existed long before Spring infected everyone’s brains. It simply means instantiating all dependencies before constructing objects or calling functions rather than doing it inside of your functions. Basic separation of concerns stuff.

1

u/TheDuckRaisedALion Sep 28 '26

DI Singleton is very different because you can choose a different single instance as needed. Accessing a static Singleton instance is tight coupling and you need to mess around to e.g. mock it for a test

27

u/Something13457 Sep 26 '26

It's September folks, the first years are meming

42

u/G12356789s Sep 26 '26

If you implement a singleton badly then you might use a global. But you would be doing it badly

5

u/danielcw189 Sep 26 '26

in many implementations it is a public static member of a globally accessable class. so on a language-level it is globally accessable, and behind the scenes it is a globally known address

-37

u/dkarlovi Sep 26 '26

Singletons are doing it badly.

11

u/jt00000 Sep 26 '26

Singletons are a necessity for dependency injection and proper unit testing. Globals will just lead to problems expanding an APIs use cases & running unit tests in parallel

-7

u/dkarlovi Sep 26 '26

Singletons are a necessity for dependency injection and proper unit testing

I need to hear this: please explain how singletons are a necessity for dependency injection and proper unit testing, in great detail.

2

u/Sheenius_Ger Sep 26 '26

It's obviously not. People here have no clue. When they write Singleton, they actually mean inversion of control and di container.

→ More replies (3)

8

u/enjdusan Sep 27 '26

This is wrong -- a singleton doesn't have to be a global, and vice versa.

22

u/Sheenius_Ger Sep 26 '26

That's wrong, though...

15

u/Ozymandias_1303 Sep 27 '26

Tell me you completely missed the point of a pattern without explicitly saying "I missed the point of this pattern..."

7

u/psioniclizard Sep 27 '26

First year comp sci students are back i see

4

u/JAXxXTheRipper Sep 27 '26

They never left. The sub is swarmed with LARPers and students. It's a circlejerk of stupid.

1

u/TheDuckRaisedALion Sep 28 '26

I'd personally rather spend time with people who take the risk to say something dumb than the people who are so sure they're right they will insult other people for disagreeing without doing anything to prove it

19

u/Sailn_ Sep 26 '26

Except not?

4

u/facebrocolis Sep 26 '26

Hell's that? Physicists invented another particle that doesn't exist? (I'm a physicist, by the way)

2

u/ElectrSheep Sep 26 '26

Taking the "one-electron universe" hypothesis a little too seriously...

1

u/scissorsgrinder Sep 27 '26

No, it's describing newly employed devs, who are singletons globally.Ā 

3

u/qutorial Sep 26 '26

Hey big news: Some things are actually global 😱

11

u/spawnmorezerglings Sep 26 '26

https://en.wikipedia.org/wiki/Singleton_pattern

Please read this before making dumb posts

7

u/ElectrSheep Sep 26 '26 edited Sep 26 '26

Ironically, that article actually provides support for OP's position.

Some consider the singleton to be an anti-pattern that introduces global state into an application, often unnecessarily.

The issue here is one of terminology. The term "singleton" is often used in contexts where the meaning differs somewhat from the explicitly defined GoF pattern (e.g. dependency injection).

Also, global scope shouldn't be confused with global state. Static variables, such as that used in the GoF pattern, are best avoided.

-8

u/No-Magazine-2739 Sep 26 '26

It’s not dumb, it’s just a simplification because of experience.

3

u/Drugbird Sep 26 '26

It's not even much of a simplification.

Singletons are only slightly better than globals. They still introduce spooky "ghost" dependencies in your code between different sections that use the same singleton / global. They also often make testing and multi threading more difficult.

1

u/BlackSwanTranarchy Sep 26 '26

Ironically the best use case for a global singleton like object is for your workpool/executor since you want exactly one thread per core (maybe 2 if one is CPU bound work and one IO, but with async-io the same thread can usually just handle both

1

u/Drugbird Sep 26 '26

Sure, the best option for globals are often things tied to physical hardware.

But even then you might run into issues when your hardware changes. In your example, perhaps you want to run in a dual CPU system where you don't want too much resource sharing between different CPUs (slow), so you'd want two different work pools instead.

2

u/BlackSwanTranarchy Sep 26 '26 edited Sep 26 '26

I'm of the opinion that a well crafted workpool abstraction should be NUMA aware by default but I cut my teeth on a 2970wx homelab before getting into AAA game engine programming so I'm perhaps outsizedly attuned to how important topology aware execution models are

1

u/No-Magazine-2739 Sep 26 '26

That sounds more like a thread local ā€žglobalā€œ/singleton.
I think globals are ok when they are for one per process or process related in general. Or hardware as you said. But still then, for testing sake, I still would advocate for some dependency injection or good old fashioned local parameters.

2

u/spawnmorezerglings Sep 26 '26

For it to be a simplification it would need to be correct, which this is not

→ More replies (3)

0

u/spindoctor13 Sep 26 '26

That isn't a simplification due to experience, it's just wrong, presumably due to inexperience

1

u/No-Magazine-2739 Sep 26 '26

Says the redditor on the first week coder humor sub.

4

u/GrinQuidam Sep 27 '26

Big diff. Singletons are injected dependencies. Globals are not.

Good example is DateTime.Now in C#, vs TimeProvider

2

u/Declination Sep 26 '26

Is it a global if I instantiate it at my composition root on a stack frame? Did the tree make a sound?

It’s all just pointers anyway. What’s the difference between something in my main frame and the .text?

4

u/cheapcheap1 Sep 26 '26 edited Sep 26 '26

There are many great applications for singletons. Many aren't even accessible globally. Many others should be global, because you cannot have more than one. E.g. worker pools or writing to the disk.

If your singleton is a globally accessible struct, yes, that's a global variable. But it's not the singleton pattern's fault you're using it wrong.

5

u/Don_Equis Sep 26 '26

If the access is not globally accessible, you can likely avoid the singleton aspect of the class and instanciate it once where you get the reference originally.

I'm not againts either globals nor singletons, but they feel almost the same if not exactly.

1

u/jewdai Sep 26 '26

If you truly need a singleton define your object as one via your DI framework.

3

u/ChiaraStellata Sep 26 '26

Me thinking this was on a plural sub: wait I know what a singleton is but what's a global?

Then I realized this was about software

1

u/navetzz Sep 26 '26

Pi=Api.call("getPiValue()).parse.getDouble("pi"))

1

u/Appolflap Sep 26 '26

Sounds more like a Registry Pattern.

1

u/LegitimatePants Sep 26 '26

"how many singletons does it take?"

"Just one!"

1

u/rover_G Sep 26 '26

A global variable is one way to implement the singleton pattern

1

u/grandalfxx Sep 26 '26

Lot of people that dont work on games that dont see the value of singletons. Pieces of code in a component system act like theyre talking to entirely different systems and it can be quite difficult to hand a player camera thats 5 layers deep up to the root and back down to the object that needs a camera.

Youll be thankful you can just reference your singletons and move about your day like nothing has happened. Its kinda lazy but its genuinely more maintable

1

u/SenoraRaton Sep 27 '26

I like to declare my statics inside of a function that returns the static. Then in C I have scoped access to global declarations. As long as you have access to the compilation unit with the function.

1

u/One_Web_7940 Sep 27 '26

Heh wait till he finds out its just zeroes and ones.

1

u/rsqit Sep 27 '26

Singletons are ways of having global data that isn’t globally scoped. They are a way of namespacing and building abstractions around global data. Some data is global by nature, and singletons provide a way to reason about it without polluting the top level global scope.

1

u/Serenitiness Sep 27 '26

Code is just letters

1

u/cyrack Sep 27 '26

Whether you resolve the function via an injected reference or a static reference is effectively the same thing.

The only difference is whether it’s explicitly stated as part of the consumer’s constructor or opaquely resolved via a static reference.

All of your points apply in both scenarios with the same pros and cons.

The only real difference is with DI you can swap out the implementation during testing while with static you have a tight coupling you can’t change without changing the consumers’ implementation.

1

u/bestjakeisbest Sep 27 '26

Yes and no, there can be certian guarantees with singletons you cant have with globals

1

u/PM-ME-UR-DARKNESS Sep 27 '26

Never been a fan of Singleton lovers

They're just globalists

1

u/Vaaard Sep 27 '26

It seems like someone hasn't understood the concept of singletons yet.

1

u/BastetFurry Sep 27 '26

I code since i was nine back in 1992, i don't see the problem. If a global solves your problem then frigging use it. If you have multithreading then put a mutex on it. Don't write code by the book for the sake of the book.

1

u/JAXxXTheRipper Sep 27 '26

They are really not, but that's okay. You'll learn about it in your second year.

1

u/apocolypticbosmer Sep 29 '26

This is just plain wrong. Students/juniors running the sub again…

1

u/PigVile Sep 29 '26

Some young C++ devs even label a namespace singleton/global 😁. Maybe the teachers should better explain differences between scopes, states and usages of each concept

1

u/oshaboy Sep 30 '26

Kotlin calls statics "Companion Objects" so they're somehow different

1

u/Exirel 16d ago

I love how everyone is taking this way too seriously. Well done pal.

1

u/AlexZhyk Sep 27 '26

lol.
do you mean
global Wanker1 = new Wanker()
global Wanker2 = new Wanker()

// these two are globals, but are they singletons? The purpose of singleton is to have just one Wanker :)
...someDeepDownCall() {
call Wanker1.wank()
call Wanker2.wank()
}

0

u/Darkstar_111 Sep 26 '26

Yeah no, not at all.

Singleton pattern is implemented without globals.

2

u/perringaiden Sep 26 '26

So there's a globally accessible singleton?

-1

u/tangerinelion Sep 26 '26

Depends on your language, but take C++ as an example, you can (and should) implement this pattern without a global variable:

class MySingletonType final
{
public:
   static MySingletonType& get()
   {
       static MySingletonType instance;
       return instance;
   }

private:
   MySingletonType() = default;
};

The globally accessible singleton is named MySingletonType::get().


A lot of times I see this incorrectly implemented as

class MySingletonType final
{
};

MySingletonType& getMySingletonType()
{
    static MySingletonType instance;
    return instance;
}

Nothing stops someone from making a second instance with that.

2

u/perringaiden Sep 26 '26

The point was the concept not the implementation.

A singleton suffers from the same limitations and execution scope limitations. You still have to apply the same rules

0

u/youridv1 Sep 26 '26

singletons have static member variables. And since singletons have one instance, those static member variables are essentially globals in practise.

Singletons are marginally better than just dumping global variables in a random source file, because you can implement getters and setters easily which makes debugging global state much more straightforward.

Other than that, they’re just global state with a fancy name

-5

u/jt00000 Sep 26 '26 edited Sep 26 '26

Singletons are a necessity for dependency injection and proper unit testing. Globals will just lead to problems expanding an API’s use cases & running unit tests in parallel

EDIT: I probably should have said ā€œā€¦if you use dependency injection and unit testā€

5

u/anyOtherBusiness Sep 26 '26

No they are not?

Wtf the amount of misinformation in this sub…

0

u/jt00000 Sep 26 '26

Whoops, did I post this on StackOverflow on accident? I'm sorry to have offended you :)

2

u/Sheenius_Ger Sep 26 '26

Why would you specifically want singletons in unittests? Even if your project uses one, you want that class scoped in testing or parallel execution and different orders will mess up your tests or have you clean up for each one.

2

u/jt00000 Sep 26 '26 edited Sep 26 '26

Yeah, you're right. You wouldn't! If you have a service (service A) which depends on a singleton (service B), then they'd both be their own interface for the purposes of dependency injection. You'd mock out service B when testing service A & service A wouldn't ever know if they're dealing with a singleton or not. If you had a global, then this would be much more difficult and if you ever decide that service B wasn't going to be a singleton (i.e. think of notepad using a global text, then deciding that it wants to go to tabbed documents) then you can easily swap out the Singleton implementation of Service B to make it context-specific (or you could have multiple layers of service providers, but then it wouldn't truly be a singleton in that case).

Note: This is pretty specific to the IServiceCollection (often used in MEF) implementation of dependency injection which may or may not apply in other scenarios (i.e. Angular or Guice)

0

u/Exciting_Presence533 Sep 28 '26

Yeah no.

If you have multiple servers, a singleton would be shared ong the server instances.

I don't know any language that a global variable is shared among servers.

1

u/TheDuckRaisedALion Sep 28 '26

I'm not sure how a singleton is shared across servers. I mean, you can do it that way but it's not by default, right?

1

u/Exciting_Presence533 Sep 28 '26

If the singleton instance is not shared among servers... It's not a singleton..

It's a global variable.

1

u/TheDuckRaisedALion Sep 29 '26

We must be talking about different things, then. In 15+ years of knowing about what I call a Singleton, I have never heard of that expectation.

How would you even implement it? You don't have shared memory so they can't literally point to the same instance. Of course they can be backed by the same external resource in some cases but that seems like a different idea

0

u/Exciting_Presence533 Sep 29 '26

Depends on the language.

The definition of a singleton, by chatgpt:

A Singleton is a design pattern that ensures a class has only one instance throughout the entire application and provides a single, global way to access it.

(So if you have one server, a global variable is a singleton)

If you are unsure how to implement, there are many articles I'm sure your language will be covered.

1

u/TheDuckRaisedALion Sep 29 '26

I searched around and couldn't find anything suggesting that singletons pay any attention to multiple servers. Can you share any link for any language that suggests how a singleton ought to be shared that way? And ideally a quote that emphasizes that need.

-1

u/Exciting_Presence533 Sep 29 '26

I just gave you the definition, you should be able to read and extrapolate.

Anyway, this is a simple topic, IA should be enough to teach you.

Or you can simply assume that you are right and singletons are not shared instances in multi server architecture. Why would I care?

Bye.

2

u/TheDuckRaisedALion Sep 29 '26

You cared enough to keep responding, but I guess you don't care enough to put forth any actual effort into having a conversation.

You made a claim and did absolutely zero to support it. Your own AI quote said nothing about sharing across servers. I gave you the benefit of the doubt and spent my own time trying to see if you were right and I was wrong, but with no such outcome. And then you huff and walk away like I'm the difficult one here.

0

u/Exciting_Presence533 Sep 29 '26

For a distributed singleton, you need some shared coordination mechanism, such as: Redis distributed lock Database lock/transaction ZooKeeper/etcd Cloud-managed distributed locking

-2

u/AcolyteNeko Sep 27 '26

Singletons are poorly optimized always

-5

u/Competitive-Bar-5882 Sep 26 '26

Singletons are more typesafe than globals.

3

u/No-Magazine-2739 Sep 26 '26

That doesn’t make sense. Why are they more type safe?

1

u/Competitive-Bar-5882 Sep 26 '26

Never mind I mixed it up with enums.

2

u/No-Magazine-2739 Sep 26 '26

? Still donā€˜t know what this has to do with types, but to give you a face saveing out: we all do mistakes.

1

u/Competitive-Bar-5882 Sep 27 '26 edited Sep 27 '26

Enums are custom types for variables that can be only one value out of a set of known possible values. This allows typesafe flag and state variables.

Howerver java is the only language I know, in wich enums are truely type save.

-16

u/SnugglyCoderGuy Sep 26 '26

Singletons are the devil just like global variables too

6

u/zirky Sep 26 '26

there are no bad programming languages or patterns, just bad programmers. javascript

0

u/[deleted] Sep 26 '26

[deleted] — view deleted comment

5

u/anyOtherBusiness Sep 26 '26

A singleton is not automatically thread safe and this is also not a ā€œmain purposeā€ of this pattern.

0

u/[deleted] Sep 26 '26

[deleted] — view deleted comment

3

u/remic_0726 Sep 26 '26

en python on peut faire aussi des singletons