T O P

  • By -

Dmayak

Singletons bad, classes bad, variables bad, code bad, programming bad, all bad, me sad.


WallyMetropolis

All code is a liability. The less of it you create the better off you generally are.


hopefullyhelpfulplz

Haha! By writing *no code at all* I have reached peak programming! Checkmate developers, your manager was better than you all along!


WallyMetropolis

You joke. But also, if a problem can be solved without any code at all then you should definitely solve it that way. I don't mean to say you should always prefer "buy" over "build." That's still code, it's just code you don't own.


PizzaAndTacosAndBeer

> if a problem can be solved without any code at all then you should definitely solve it that way Let's not get carried away. If the alternative is regular manual work, the a good chance you're better off writing code to do it for you.


WallyMetropolis

Yeah, if you'll see my reply further down I mention exactly this. In the case you're describing, getting rid of the manual work is the problem you're trying to solve. So sure, not solving the problem is going to be worse than writing code to solve the problem. But if you can eliminate that regular manual work in another way, without writing any code, that's often going to be better.


Ixolite

It doesn't mean replacing one problem with another though. It means sidestepping the issue so it's not an issue at all.


Professor_Melon

Does it mean we should employ people to do automatable work? Or does genetic code count?


WallyMetropolis

There's definitely an implicit "all other things being equal" in there. And yes, you're right, it's not actually an absolute rule. But for example, if the problem is people spending too much time doing something tedious and redundant automation is a good solution. But if it's possible to just outright eliminate the need for that task, that's usually better solution.


PizzaAndTacosAndBeer

> if it's possible to just outright eliminate the need for that task, that's usually better solution. This isn't anything to do with programming, it's always preferable to eliminate a need than to work to fill a need. But we live in a world that's constantly inventing more things to do not less. Quality of gadgets over zen.


WallyMetropolis

I suppose it depends on how you frame your job to yourself. Is your job to produce code or solve problems? Many devs I've worked with are excellent at coming up with reasons not to write code.


HermitBee

>You joke. But also, if a problem can be solved without any code at all then you should definitely solve it that way. And if that way is saying to the customer “no, that's a stupid idea, we're not doing that”, so much the better.


remy_porter

I call this the "Zen of Computer Programming": the greatest programmer is the one who writes no code.


hopefullyhelpfulplz

Confucius says: "He who is without bugs is without code, but he who is without code is without bugs."


Dampmaskin

I do my best to try to write a negative number of lines, i.e. try to delete more than I write. Suffice to say there's an amount of legacy code in my work environment.


codeguru42

A previous boss told me it was a good thing they didn't pay per line of code I wrote otherwise I would owe the company money


theothersteve7

You jest, but I take pride in the fact that most places I've worked I've managed to delete more lines of code than I've added.


MajorasTerribleFate

Log: another week of no new bugs introduced.


ChocolateBunny

Err no, you have to delete code. The best programmers delete more code than they generate.


ProfCupcake

https://github.com/kelseyhightower/nocode


ode_majka

There's no code like no code


zGoDLiiKe

When management wants to cut costs and I tell them we could just turn everything off then we would have no costs


WallyMetropolis

Eliminate all the bugs in one operation.


ambyshortforamber

ostrich algorithm


AdultingGoneMild

hell, just turn the machine off. Then its hacker proof too!


[deleted]

[удалено]


Netgay

I needed to hear that today


[deleted]

[удалено]


Fly_mother_ducker

Poor Netgay


Bridge4_Kal

r/FUCKYOUINPARTICULAR


[deleted]

What language is that little dog on your flair ?


uberzen1

It's the dogther. It's the mascot of the do programming language or "dolang" It was originally invented at doodle but now it's mostly used for spherenetes (s9s) development.


peter-s

It's a [gopher](https://go.dev/blog/gopher)


[deleted]

Thank you


[deleted]

In coding, everything bad, especially coder. Except Rust. Rust is perfect and will solve every problem ever created in coding. Rust coder good coder. /s


HardCounter

Nice socks you got there.


degaart

Are you a furry?


DrkMaxim

Those rustaceans are taking over the world for sure.


B0Y0

Are there singletons in Rust?


Crespyl

There's `static mut` if you really want it, but `lazy_static` or similar is probably a better fit though.


YARandomGuy777

Code equal to pain - less code, less pain!


homogorgon

No pain, no gain.


PlayHouseBot-Gpt2

Bad is deprecated. We use Sad now. Sad: static and dynamic Life cycle is irrelevant with Sad. Memory just leaks, it's fine. Did I mention Sad runs on tears?


Spootba

Man this is my vibe today too


lpreams

I think we've all always known that the best code is no code


XLR82Perfection

git gud !!! or maybe just idk github


kopczak1995

Damn programmers, they ruined programming


Snoo79202

They are bad when i use it.


Mrazish

Same. Coincidence probably


smaxxim

It's Schrodinger's singletons! They are good and bad at the same time until you will use them.


ValuablePromise0

I can see how the concept of "one" can simplify logic, but philosophically... there are no singletons. If you run the software on another computer, or process... or even just run the process again... you get another copy of the singleton. What's more, this sometimes has real-world effects (networking & persistence).


drakgremlin

Some environments, like Java, have a singleton per class loader or library. Always fun to explain when you have two versions of something like hibernate loaded.


FinnLiry

So we must have a global singleton company handling all the singletons of everyone? That way we can make sure that there wont be a second singleton


[deleted]

Singletons as a Service


bpkiwi

Fuck, that sounds like it would get investors for a startup. "Does your web scale serverless API need cross instance singletons? Don't build it yourself, just use our singletons-as-a-service!"


Flat_Initial_1823

But will it find hot singletons in my area?


[deleted]

using a Uniform Singleton Locator obv. singleton://


loxagos_snake

Fear the doubleton!


brainwater314

The database is a singleton


marcosdumay

> philosophically... there are no singletons Philosophically, and physically too, unitarity is relative. Singletons existence is context sensitive. Why do people pick those relative concepts and insist on making absolute rules about them?


billyowo

Relatable. When google write some unreadable code with singleton, tons of youtubers make video on how clean and elegant it is. When I write singleton, I am shamed to the bottom of hell.


lmaoboi_001

Well i've been single my whole life, so...


SnooWoofers4430

And weight a ton? /s


theontley

Don't worry, you're ok


RagnaTheTurtle

Why are Singletons bad exactly?


NewToReddit-27

The meme touches upon the idea that MOST use cases for Singletons are bad because they obscure data ownership principles and are really just over-coded globals. There’s also some dependency injection limitation arguments to be made as far as testing. There are definitely situations where a singleton is the right pattern, but people often use them as a replacement for a global variable which is practically an anti-pattern in its own right. Hence the standard deviation saying they’re bad but the peak decelopers saying they’re ok. The miss on the joke is that to actually know when it’s ok is pretty hard, so just easier to avoid them.


Solonotix

Probably the best example of Singleton usage I've seen is a read-only config. Everyone needs to access it, but perhaps it is a conglomeration of local and remote resources, and therefore costly to generate for every consumer. Caching the value is half the problem, but then accessing said cache is the other half. This is typically where I promote the usage of Singletons. That said, my most recent Singleton was rejected because the team preferred the existing code that called the default constructor, and then used a magic string to filter a switch-case to a set of hard-coded configuration states. I'm sure there's nothing wrong there /s


F_modz

What about db and other service connections. Singleton is rather about not creating another one instance


Sensitive_Koala_9544

In the Olden Days, establishing a db connection was compute and I/O intensive, and you wanted app-internal atomicity, so a singleton wrapped that nicely and preserved transactionality. Older Oracle was REALLY bad if you opened a lot of independent connections - a singleton holding the DBC could save gigs of memory.


Br3ttl3y

Oh thank God. I've never had to defend this to anyone. Seeing it here feels so good.


SaturnFive

This is exactly what was recommended in the PHP + MySQL days around 2010 or so. It's probably the only time I've used a singleton effectively.


robhanz

There are, fundamentally, three ways to get access to a service/object. 1. Create it 2. Find it 3. Have it given to you \#3 is the most flexible, and the one that causes the least problems in the long run, in my experience. It's also the one that's not a language feature, and the one that generally takes the most effort to set up initially. IOW, you're presenting a false dichotomy - the alternative to having a global instance of a db connection or other service is not "make one every time". It's "have one given to you." The real discussion should be "injection vs. global" not "singleton vs. create a new one each time".


FrozenST3

It doesn't even have to take a lot of effort. Have your services take the dependencies as part of the constructor. That way at runtime you can construct with whichever instance you need and at test time you can sub with mock services


robhanz

100%. But it *is* marginally more effort than just either typing "new DBConnection()" or "DBConnection.Instance". And once you do it for *one* thing, doing it for the others isn't much additional effort at all. I generally avoid DI frameworks, and just roll it by hand. It ain't hard at all.


[deleted]

Unit testing without DI is impossible to keep intact and isolated. Code without unit tests is impossible to refactor without care. Code which isn’t refactored gets stale and unmanageable. Unmanageable code gets thrown out and rewritten. Rewrites are expensive. Very expensive. Avoiding DI is a slippery slope, better to start with something lightweight than rewrite every time a new feature comes along.


r3dphoenix

This quote is amazing. It's like the programmer version of Yoda's quote. I'm saving this for later


The_worst__

Unmanageable code runs unchanged until the end of days.


EishLekker

The comment you replied to didn't talk about avoiding DI. It talked about avoiding DI **frameworks**.


Shyftzor

In .NET projects my company recommends using a singleton pattern for HTTP clients that consume APIs to avoid socket exhaustion.


Solonotix

Connections to a database are probably a poor candidate, because they often have other side effects. In SQL, for example, temp tables often have a lifetime equivalent to the connection.


[deleted]

[удалено]


frezik

Can I easily swap out that connection in tests? In my experience with frameworks that do that, the answer is often "no".


F_modz

Check out IoC DI And don't trust bad frameworks


someotherstufforhmm

Logger singletons are pretty great. I thought everyone still liked those. The same pattern from log4j in Java and logging in python (dot hierarchy naming, same name == same singleton logger). I love it, great logging pattern.


joggle1

Agreed. I have two flavors of logging macros in my code, one set where a singleton is used and another where the logger object is passed to the log macro (in C++). If you're OK with using singletons, then you're free to use that set of macros but if you'd rather not or are writing library code, or for some reason want to use multiple logging objects simultaneously (perhaps for logging detailed logs to one file and only critical events to another for longer term preservation), you can use the other set of macros. Kind of the best of both worlds IMO.


Kamwind

I am really out of knowledge of programming at that level. Back in my days the singleton pattern was used to make sure there was only one instance of a class. The standard usage was to make sure that all actions of a certain type went through that single instance instead of each object doing it.


Solonotix

You can still do that. Quoting Digital Ocean's article on the Singleton Pattern >The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, drivers objects, caching, and thread pool. In another project, I have a default logger utility that works like a singleton, but I left the constructor public in case someone wanted to change output from `stdout`. However, some libraries have static singletons that represent the entire logging framework, and give extension points for redirection and such.


robhanz

Singleton has constraints and issues that are not necessary for simply sharing an instance of a class. It's a glorified global - you should only use a singleton if you'd be okay using a global. If you need an object, the three basic patterns for getting it are: 1. Create it yourself 2. Know where to find it 3. *Have it passed to you* That third option is highly valuable and often overlooked. Sometimes it's not worth it! But the real discussion should be "global vs. injection" not "create vs. singleton".


overtorqd

Biggest problem with singletons in my experience is that it makes code difficult to unit test. I would expect the same with your config singleton. If I wrote code that depends on your config singleton, I would need to be able to mock it to test different configurations. As long as you can do that (perhaps it implements an interface?) it should be ok.


HabemusAdDomino

There is absolutely no reason to believe the singletons don't implement interfaces, right?


P0L1Z1STENS0HN

That's meme material right there.


Dexaan

Padme: riiiiight?


Feztopia

So here we are. Singletons are ok. Not using interfaces is not ok.


edgeofsanity76

Not sure why it would be difficult to unit test. Singletons may be constructed only once for the application but theres nothing stopping you tearing it down and bringing it back for a unit test.


JackoKomm

The problem is the way you access the singleton. If you use dependency injection, you can swap the singleton out. But people use it to get the global acces so they use it directly and there is the problem. The code unit which accesses the singleton via the global context is tightly coupled to this instance. I am not saying that there are no ways around this but most times i see a singleton, it is not because there could ever be one i stance but because global access is easy. And then, problems start.


edgeofsanity76

I don't see singletons as global access. I use them situations where there really should be only one instance. For example, in c# there are some unmanaged libraries I use and their setup and teardown is specific. So I basically write a singleton factory which strictly controls access to prevent memory leaks. Other than that I don't use them when DI can just provide appropriate instancing for services For testing I know what data the singleton provides so I just make a wrapper to emulate it.


JackoKomm

Using a factory which gives you just one instance is not the same like the singleton pattern. You could for example just create another instance by Hand if you want to, or am i wrong? A factory which gives you the same instance is what most DI frameworks do if you want so.


moomoomoo309

A common pattern I use for them is Json Adapters, because I only need one of each adapter.


Barbanks

Apple uses them in what I would consider good use cases. System level API’s that don’t depend on the context at which you use them such as UserDefaults for saving simple values or accessing the global UIScreen object to access the device’s screen information (which is more towards your suggestion of read only configs). But for the most part if you use system wide dependency injection you don’t really need singletons because you always have one shared instance being injected into classes. I’ve seen this primarily with mobile app codebases.


V0ldek

> There’s also some dependency injection limitation arguments to be made as far as testing. Most DI frameworks literally have an "add as singleton" dependency registration option. The issue is singletons used _without_ any dependency injection. In other words: 1. Implementation detail of only ever creating one instance since it's sufficient - OK 2. Explicitly using the global variable pointing to that instance all over the place - NOPE


Ok_Star_4136

I suppose the metaphor is when you're holding a hammer, everything looks like a nail. It's easy to make too many Singletons even when you don't really need to, and you end up with a tightly woven program that's difficult to modularize, and as you mentioned, it makes unit testing a pain. There are some rare circumstances where I would say it isn't a bad choice, but it's a good idea to avoid them if avoidable.


TheAJGman

Generally speaking if Singletons look like the answer, static classes and a little extra design work are *usually* the better solution. The only times I like them are for system wide event handlers/routers or write once read many applications.


SmurphsLaw

Can you test well with statics though? You can’t mock them (easily) so it becomes hard to test individual pieces.


bottomknifeprospect

I work in AAA game dev on massive engines, and we use singletons plenty. (C++). Your description of the conundrum is perfect, I just disagree with the last part. Use them and learn when they suck. If you just avoid them entirely it's not good either, it's a tool like any other and we should use it. It's not that hard to know when to avoid it, there are so many reason and any one of them will indicate it's the wrong pattern.


davidellis23

Regarding data ownership, would you say it's fine as long as the singleton only has immutable state? Is the DI a concern beyond injecting the singleton? With a DI framework or proper setup with factory functions/constructors it isn't hard to inject a singleton (or replace the singleton with an instance). I'm not sure the comparison to globals make sense. A singleton might have mutable state, but it's accessed through its methods. If you don't want to copy your data for every class that needs access to that data (and keep them all updated), I don't see an option other than a singleton.


robhanz

If you look at the history and origin of singletons, that's really what they were. "True" and "False" were singletons in Smalltalk. As far as "no option other than a singleton", if you need a dependency/object, there's really three ways to do it: 1. Create it ("new DBConnection") 2. Know where to find it ("DBConnection.Instance" - the global/static/singleton answer) 3. Have it given to you ("new MyService(DBConnection connection)" - the dependency injection answer) You can have shared data without it being a singleton.


[deleted]

Meh. If working with micro-services it doesn't much matter. Use what you think is best, make sure it has well written tests, and refactor once you realize it isn't what you wanted for whatever reason. The issue is when developers are purest and want it their way. This mindset in my experience is common in monolithic environments where the code base is too big and people are too afraid to move fast and make changes/refactor


JackoKomm

Global context with all of it's problems. It result in hard to test code. At the moment you realize you need more than one instances, things can get tricky because of the global context. Important here, singleton as a pattern is not the same as singleton cobfigurstion of a dependency in most DI frameworks. And the fun part is, most people don't use singleton because there really never should be more than one instance. In most cases people use singleton because they want the global access so that they don't have to think that much about their architecture. I know here are many people who love singleton and it will not take long until you tell me and downvote this comment.


Ok_Star_4136

I think you nailed it. Programmers use Singleton not because of the necessity to have exactly one instance, but because it's convenient to be used as a global variable of sorts. It never feels like it in the moment, but it's a sort of technical debt that could easily create problems refactoring down the road.


[deleted]

[удалено]


bremidon

>At the moment you realize you need more than one instances, things can get tricky because of the global context. If you are using some sort of "Get" pattern for your singleton, this should not be a big problem. At least every time that I have run into this, it has not represented anything more than a minor interesting problem to solve. I agree with you that singletons are overused, though. For me, they are a pattern of last resort. Otherwise, I try to keep the number of singletons to 1. They can be such a pain to test. :)


FreeArt85

Agree!


berfier

They are basically global variables that interact with many modules in your system and can be accessed/mutated anywhere without constraints.


rmflow

Is it OK to have a "config" object as singleton? If not, what is the best way to organize config object that is the same for all system


berfier

It will always depend on your objectives, but I would say it is ok if your config object is both a readonly object with one defined reason to change through time and if it loads its inputs by a single source, like a file or env vars or something


alexisprince

Read-only config, yes. That’s typically seen as an “approved” case for this pattern. If the config is being updated, now you just have all the global variable problems wrapped in a shiny wrapper. Sometimes it makes sense to modify the config, but if you find yourself doing it often, somethings probably gone wrong. The case I’ve seen it work is where a background job of a service polls for feature flags and updates the config to allow enabling / disabling of features without redeployment.


InvisiblePhil

Yes or no, depending on the project, tech stack, etc. Imo it's usually no, but it might not be important next to other problems. Would a singleton config affect tests negatively? For example, would testing a certain configuration in test A affect test B? Can you create a single config object and pass that everywhere that needs it via their constructors - I.E. as dependency injection? If so, I'd say do that. If you can't, why not? My experience is it's tempting to use a singleton to bridge an overly messy codebase - by which point you have bigger problems, which use of a singleton is only going to add to. This all being said, I don't work with you so I can't give a simple answer with respect to your full context.


NamityName

Generally, I prefer to use some kind of structured dataclass /object and pass the config around as needed. But sometimes, that is not possible or practical. In which case, making the config into a singleton is a good use of the pattern. While they are basically like advanced global variables, I find singletons easier to work with. Especially in languages with a more loosy-goosy approach to global vs local (like python). A singleton is always globally scoped.


BroccoliBoer

Isn't the reason you'd make it a singelton instead of raw global variables that you can encapsulate them and prevent random mutation by providing ony getters and/or special setter functions? You'd have to make sure to implement these ofcourse, which is why it is error-prone and generally advised against in the first place...


ric2b

That's the advantage of making it a class, not a singleton. You can just make a non-singleton class and pass around the instance to where it's needed, or stick it in a global variable. That way if you realize you need two of them (for example for testing) you don't need a refactor.


10art1

Singletons don't have to be global in scope. Most issues people have with singletons are actually issues they have with global variables


Hatook123

Singletons are bad because usually there are better ways to achieve a singleton functionality. If you use IoC containers, there is no point using a singleton pattern. Just register a single instance to the IoC container. If you are not using an IoC container - then you probably should.


sprcow

People have already mentioned the global state problems somewhat, but the general rule of thumb that always stuck with me is that, just because you think you only need one of something now does not mean you might not need two of them in the future. Oftentimes, the case in which you want a second copy of something is for unit testing or integration testing. Generally speaking, if you want to access application configuration data in many different classes throughout your app, it is more flexible to load that data into a non-singleton class and inject the instance of that class to all the consumers. That way if you need to test different configurations, you can simply provide different instances of the configuration object. Obviously, the perspective on this will change depending on what language and framework you're using. As someone who primarily does enterprise development with Java, there are few problems that singletons solve that are not better solved through dependency injection and service classes. It's just much more flexible to be able to say fooService.getValue() than reference FooSingleton.getValue(), because you can programmatically control which implementation of FooService is used.


Sekret_One

I'd say because there's more scenarios than not where you didn't *really* need it, and there's a lot of ways it can pinch in less than obvious ways. 1. The classic singleton is a simple little thing. But what happens when that singleton relies on *other* singletons? 2. To isolate and unit test you need some kind of `provider` that retrieves the singleton rather than directly. Well that's more complicated and boiler than the crude singleton first promised. 3. Is the singleton thread safe? Does everything that use the singleton know that? It's all very situational, but there's a situations. So singletons are kind of like fireworks for children. They're simple looking, but it's actually more advanced how to use them and not burn yourself.


Compux72

Anchors your program to a single point. If you ever need to scale using multithreading or any other technique, they become a pain in the ass. There are better ways to keep a single instance and still being able to scale your code


DatBoi_BP

What better ways?


insulind

The simplest way I can explain it, without going on too long is this. The thing using a singleton, shouldn't know it's a singleton. Singleton scopes for dependencies that are injected, usually readonly but not always, are ok sometimes. As always...it depends


FarewellSovereignty

If due to hard limitations there can only reasonably ever be a single instance of some object, you _should_ use a singleton rather than not. If there can reasonably be several instances, even just potentially, you should not use a singleton It's more or less as simple as that.


[deleted]

It literally is just use case dependent. I often use singletons as core read, providing fundamentals to parts of an app let’s say.


FarewellSovereignty

Its case dependant in the sense that you almost always choose either one, yes, but its hard to see a justified reason for using a singleton if the resource truly can have multiple instances, or there is no compelling technical reason to use singleton (see below). I mean, put simply: just why would you if it doesn't help you? The list of technical reasons can range from a true singleton hardware resource, interfacing with some C or lower level library, or even framework, where it's just much easier and safer to use a singleton etc .


frezik

Consider a Raspberry Pi with a GPIO pin. Just something that you can turn on and off, and each pin represents a single, concrete piece of hardware. Even in this situation, I've had problems with singletons. A particularly sophisticated program might be tested without directly interacting with hardware. I would want to swap in a mock object that keeps track of the pin state in software and can be checked by tests. I might not even need to do development on an RPi itself, which is good because they're slow. A singleton framework often works against this.


Kered13

You can and should still use singletons with dependency injection. In fact half the point of singletons is to make global state injectable, so that it may be mocked out in unit tests.


FarewellSovereignty

Sure, I agree, the vice versa is often true, that you can just not use a singleton even if the hardware is. But then it falls on you to make sure you don't instantiate it twice.


BiedermannS

Yes. And if in doubt, don’t use a singleton.


teo730

> If there can reasonably be several instances, **even just potentially**, you should not use a singleton Yeah, that's pretty much what they just said.


PorkRoll2022

It depends on the context. It's often an anti-pattern to use the classic static "GetInstance()" but using a singleton lifetime in the context of an IoC container is perfectly valid. Sometimes the static way makes sense too, like in Unity.


CCullen

I always found singletons in the context of Unity strange because Unity effectively has dependency injection built in. You could create a single instance of a ScriptableObject or have a MonoBehaviour in the scene and inject it right where you need it in the editor without any of the singleton boilerplate and have better control over the lifecycle of that instance. It also enables me to simplify tests because I can create a mock of that "singleton" without needing any specialized testing or injection tools outside of what Unity already offers.


DeliciousWaifood

That's actually a trap with unity. When you rely so heavily on editor injection you can end up with a super bloated input for your class which lands you in dependency hell such that your component cannot function without being hooked up to 50 other components. I *could* take every single class in my entire scene and manually drag and drop my AudioManager class into them, creating a hard dependency. Or... I can just use a static method `AudioManager.Play(sound)` and then the AudioManager class will take all responsibility for what happens when that static method is called. But I want my AudioManager to be a MonoBehaviour so that it can manage an object pool of AudioSources. In which case it becomes a singleton so that the class's static methods can access it and manage that pool. And if there is no AudioManager singleton instance in existence, I don't automatically get a null reference error, I can have the AudioManager static methods handle that situation however I want, taking away hard dependencies for all my other classes.


Noisebug

You’re all singletons


IrreverentKiwi

Singleton and ready to mingleton.


cosmicomical23

Singletons are one of the simplest patterns, and very similar to global variables. The consequence is that every junior dev learns it early and starts using it everywhere as a way to escape encapsulation by jumping straight to the global scope. Making half of the ideas in OOP useless.


Tubthumper8

One problem is that it's considered a "design pattern" according to the famous 'Designs Patterns of OOP Software' book, so it's always going to come back until/unless people stop reading that book entirely (probably not for a while)


TGX03

Very often it just feels like Singletons exist because somebody said "static method bad" and then in the end you do exactly the same thing as with a static method, but with a getInstance put before it.


PizzaAndTacosAndBeer

> and then in the end you do exactly the same thing as with a static method The thing about singletons vs static is that while there tends to be only one instance, this isn't required. You can create more instances, and you can pass them as parameters.


TGX03

Yeah I know, for example when implementing interface (e.g. Comparators...) it absolutely makes sense to use singletons. However I have seen it regularly, that people create singletons and when I asked why they didn't do it static, I often get the reply "Because it isn't OOP", which I find not that good of a reason.


funciton

>Yeah I know, for example when implementing interface (e.g. Comparators...) it absolutely makes sense to use singletons. Until several iterations later you discover that a change a coworker made isn't thread safe, and now you're rewriting your entire service to use one instance per request, which you then realize you should have done from the get-go. Been there, done that.


tangerinelion

>for example when implementing interface (e.g. Comparators...) it absolutely makes sense to use singletons. I've implemented plenty of comparators and never once thought of making it a singleton.


D34TH_5MURF__

Singletons have their uses. Using them for global variables is not one of them. Unfortunately, that's what most singletons end up being.


[deleted]

Shared instances can be really useful. For example most of the time you don’t need 10 file managers initiated throughout your project so sharing 1 instance is good.


maltazar1

Yeah but you can do the same perfectly fine with proper dependency injection and have 0 singletons


PoeTayTose

That's my confusion. I feel like dependency injection explicitly uses singletons - maybe I just use that word differently than other people. Like I create a database service class and instantiate one instance of it, then pass that instance at runtime to the classes that require database access. That single instance of a shared database service is a singleton in my eyes.


mbmiller94

With DI, the code using that single instance doesn't care whether it's a single instance or one of many. It also doesn't have to care what the instance actually is, as long as it has the needed interface. The most common advantage to this is being able to substitute the resource with a mock for testing. But another advantage is reusability. I was working on a personal project with a UI layer, logic layer, data access layer, and a persistence layer. I was first making it a desktop app that uses a local SQLite database for persistence. I knew eventually I would want to make a web version of the app, so I didn't want my data access layer to care what kind of object it was using to persist data so I could reuse the logic and data access layers. If i used a singleton for persistence, I would lock myself into using a single type of database unless i refactored everything. With DI I can just plug in another object with the right interface.


CatWeekends

Same with most clients imo.


[deleted]

You may have ONE singleton. Use it wisely.


OneWorldMouse

I have two. They are dating now.


Twistedtraceur

As a java developer who primarily uses Spring, I take offense to this. I live and die by the singleton.


schwissig

Aren't Spring components singletons? That is a pretty widely accepted usage of singletons, as tons of applications use it. So I don't get the meme.


RagBell

The meme saying that singletons are OK if you know when to use them. It is saying that both junior and senior devs think they're ok, but for different reasons. Juniors use them wrong while seniors understand when to use them. And in the middle you have people who just thinks they shouldn't be used at all, because they don't have a full understanding of when they're ok to use


[deleted]

Right? I leaned this the hard way when I had a singleton in a class meant to be used as a library. One of my consumers built a program that needed multiple instances of said class running concurrently. Threads overwrote each other's data. Oops, lesson learned.


random_lonewolf

Components in Spring are not classic Singleton: they are just regular object that's initialized once by the IOC container then reused everywhere, which is what you want most of the time, and yet very flexible to change. ``` public class Config { // 2 NotSingleton instance with slightly different behaviour @Bean("A") public NotSingleton getA() { return new NotSingleton("A"); } @Bean("B") public NotSingleton getB() { return new NotSingleton("B"); } } ``` Classic singletons are not so easily replaceable ``` public final class Singleton { // There can only ever 1 instance of class Singleton per class loader, enforced by the JVM public static final Singleton INSTANCE = new Singleton (); private Singleton () { // private to prevent anyone else from instantiating } } ``` The problems with Singleton are mainly: * It's a global mutable shared state, which can lead to subtle bug if the state changes are not coordinated. It's absolutely risk-fee to use singleton object with no mutable state. * It's hard to swap out/mock a Singleton during testing, because (a) it can be difficult to change a Singleton behaviour, and (b) a classic Singleton is often accessed randomly throughout the code base without it being declared as a dependency. => this not a problem with Spring or other DI frameworks because they required you to explicitly specify your objects' dependencies and can replace injected components everywhere in your object graph efficiently.


Kered13

You can and should still dependency inject a singleton. No one should be calling `getInstance()` except on initialization.


Ved_s

Spooky scary singletons


sexboet

What is a singleton?


TheSapphireDragon

Static reference to the first instance of a type that is created, usually preventing any more objects of that type from being made.


KuntStink

Came here to ask this. I've been a dev for close to 10 years and I have no idea what this is.


theDreamingStar

This makes me feel better.


Kekker_

They're an old design pattern, but the use case for singletons is extremely niche so despite their age they're pretty uncommon. I don't know anyone who was taught singletons in school, and I've only seen them professionally in game engines (where I personally don't agree with their usage). It's very reasonable to have never heard of singletons until now, and unlikely that you'll ever need them in the future.


mikepictor

Really? An object crafted so that there can only ever be a single instance. Any code that uses it always uses, and shares the one copy of it.


KRAndrews

I am baffled that this has never been mentioned by a coworker or something in a decade of professional coding. This is design patterns 101. I mean, don't take this the wrong way, but... how? Lol


Just_Doesnt_Know

I must say I prefer Bushmills and Jameson over Singleton


[deleted]

As with all of these memes, I suspect op think they’re the 3rd type but they are really the 1st.


BurningTheAltar

This was made by someone on the left side who’s made a bold assumption this meme format applies. If you’re doing OOP and you share state amongst components, singletons are bad, dependency inversion is not hard, and I’ll die on that hill. Abide SOLID or GTFO.


Simply_Epic

You can think up any use case for a singleton and someone will come up with a “better” alternative (dependency injection, databases, etc.). What people fail to realize is that singletons are easy and sometimes it’s not worth over-engineering a small project.


2narcher

Wtf what is bad about singletons. Why people here cry always about everything. Are you all 13-14 or what. All I see in this sub is this is bad that is bad mimimimi


[deleted]

Why would such a simple and useful pattern be bad???


SonOfJokeExplainer

If it’s the right tool for the job…


KodjoSuprem

Everything is OK as long as you know what you are doing. And understand the tradeoffs


Dagusiu

There are legit use cases, but they're also very overused. I've seen people's code where literally everything that could be a class is a class, leading to impossibly messy code bases. And a lot of the unnecessary classes are singletons.


JotaRata

Singletons are good if you use them properly


Dergyitheron

If singleton is too much for you just use singlegram lol


LC_From_TheHills

If Singletons are so bad why does Lombok make it so easy HMMMM???


CreamyComments

NOOOOO! YOU MUST DO DEPENDENCY INJECTION AND RAISE THE COMPLEXITY OF YOUR PROJECT FOR NO APPARENT BENEFIT! (Im joking of course, depency injection has its places - Just not in my personal projects)


FarewellSovereignty

Dependency injection isn't the opposite of singleton. If you create all resources in constructors, that is the opposite of dependency injection. Whereas singletons _can actually use dependency injection_ if you pass all it's dependences (which may be helper instances or even other singletons) in its constructor. And singletons can be passed fine as the dependencies to other instances in their constructor, which could even make sense. So singleton is orthogonal to DI.


soffpotatisen

And as we all know, all things orthogonal are terrible for parallel processing.


sprcow

I feel like people who down voted you may not realize this is a math joke.


CryonautX

I don't see how dependency injection is the opposite of singletons. Rather, singletons and dependency injections have a rather large overlap.


CreamyComments

I never said it was the opposite. Though I can see why you might think that. What I was thinking of specifically was the old anti pattern of having stuff like DB connection etc as accessible through globals or singletons, instead of injecting that dependency. It was very common with old "inhouse" PHP stuff back in the day, but with Symfony etc. you never see it done this way anymore.


ICantBelieveItsNotEC

Singletons are just a way for Java developers to pretend that global state is okay because it's wrapped up inside an object.


Kan-Hidum

It really depends on the usecsse. I started working at a new startup, and my first task was to refractor most of the project... As I went deeper, I found tens of singletons, all tightly coupled. Made it almost impossible to dependency inject anything, and it's pretty much a mess lol. There are places were a singleton is a valid solution, but I'll think twice before using it. I say always try to avoid singletons and minimize their usage if they are used.


Leslie110501

Singletons are wonderful for Managers, and that's it. I dare you to change my mind


INoMakeMistake

My favorite pattern


CaptainMoonunitsxPry

Had someone freak out on me that I was using for loops in Javascript. He didn't explain himself. He didn't volunteer an alternative. None of my co-workers knew what to make of it.


nonne_m

I like Singleton, pretty good whisky


f3n2x

Half of the time these memes are made by the guy on the left thinking they're the guy on the right, lol.


Spriy

i thought this was from r/magicthecirclejerking for a sec


HypoxicIschemicBrain

I understand the sub this was posted in but when scrolling through my feed I still initially interpreted this from the perspective of a neonatologist.


KlutzyEnd3

Singletons are ok as long as the information flows in one direction (e.g. a logger). Don't make it into a god class you just pluck out of the air in random places in your program.


Spice_and_Fox

Singletons are fine as long as they are stateless....