Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
America Inc.
Nov 22, 2013

I plan to live forever, of course, but barring that I'd settle for a couple thousand years. Even 500 would be pretty nice.

qsvui posted:

eh, using a struct with static methods is fine. you don't have to deal with the possibility of using declarations, people re-opening the struct from a completely different area of the codebase and adding poo poo like you can with namespaces, and also sidesteps any adl shenanigans.

I actually like being able to do a scoped using statement, for example in a function implementation or even just in a block. If the namespace name is long that makes the code just a little less lengthy. Certainly global namespace pollution in a header is bad.

Adbot
ADBOT LOVES YOU

Zopotantor
Feb 24, 2013

...und ist er drin dann lassen wir ihn niemals wieder raus...

Absurd Alhazred posted:

Could be someone with Java training.

Nah, a Java programmer would have made it a loving Singleton.







seriously people, don't use that stupid pattern in C++, it has no benefits at all

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Zopotantor posted:

Nah, a Java programmer would have made it a loving Singleton.

seriously people, don't use that stupid pattern in C++, it has no benefits at all

The singleton pattern is bad in every language, not just C++.

NihilCredo
Jun 6, 2011

iram omni possibili modo preme:
plus una illa te diffamabit, quam multæ virtutes commendabunt

Hot take: singleton is a perfectly fine way to represent an object as long as the following properties hold:

1. It requires non-trivial initialization, so you can't just make it static.

2. The thing it represents cannot, *by design*, have more than one instance. Most common example is the database connection. But also e.g. if you don't need to support multi-monitor setups, you can make the Screen object a singleton. If you need to work directly with a printer or a camera or a robotic arm, only supporting one at a time, you can make it a singleton.

xtal
Jan 9, 2011

by Fluffdaddy
Isn't using a singleton for side effects the same thing as global mutable state?

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

NihilCredo posted:

Hot take: singleton is a perfectly fine way to represent an object as long as the following properties hold:

1. It requires non-trivial initialization, so you can't just make it static.

2. The thing it represents cannot, *by design*, have more than one instance. Most common example is the database connection. But also e.g. if you don't need to support multi-monitor setups, you can make the Screen object a singleton. If you need to work directly with a printer or a camera or a robotic arm, only supporting one at a time, you can make it a singleton.

The singleton pattern is completely automated if you use a dependency injection framework - there are cases where semantically, the singleton pattern works, but if you're writing classes with name "singleton" in them, you're probably making a mess. Letting your DI framework enforce the "singletonness" of a class works out a lot better for test-ability and refactoring.

Bruegels Fuckbooks fucked around with this message at 02:46 on Apr 26, 2020

Soricidus
Oct 21, 2010
freedom-hating statist shill

xtal posted:

Isn't using a singleton for side effects the same thing as global mutable state?

yes, a singleton is just a global object with possibly complex/lazy initialization. if that is what you need,* then a singleton is the usual way to get it in a language like java.

* it probably isn't

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.

NihilCredo posted:

Hot take: singleton is a perfectly fine way to represent an object as long as the following properties hold:

1. It requires non-trivial initialization, so you can't just make it static.

2. The thing it represents cannot, *by design*, have more than one instance. Most common example is the database connection. But also e.g. if you don't need to support multi-monitor setups, you can make the Screen object a singleton. If you need to work directly with a printer or a camera or a robotic arm, only supporting one at a time, you can make it a singleton.

Sometimes a singleton makes sense while allowing multiple instances. For example, on Apple platforms there's a default notification center for one-to-many intraprocess communication. This is almost always the notification center you want to use, so it's built as a singleton. But once in a while you have too much traffic for the default center, or some other special need, so you might make your own. It needs to work both ways, though I wouldn't be surprised if most devs on Apple platforms have never made their own instance.

The file manager is another good example. You almost always want the default singleton instance, but sometimes you need your own instance so you can set a delegate or whatever.

It's also not always clear when you'll end up wanting to make instances sometimes, so it's smart to implement your singleton as an actual instance (e.g. use instance methods, not static).

taqueso
Mar 8, 2004


:911:
:wookie: :thermidor: :wookie:
:dehumanize:

:pirate::hf::tinfoil:

GoF was a mistake

xtal
Jan 9, 2011

by Fluffdaddy

Soricidus posted:

yes, a singleton is just a global object with possibly complex/lazy initialization. if that is what you need,* then a singleton is the usual way to get it in a language like java.

* it probably isn't

It's Rust's lazy_static, if it had to be wrapped in OOP. The same process is used more loosely in C. The equivalence is that the term is a global that's initialized on first usage, but always referenced as a global, and the memoization is transparent.

An alternative would be having the definition be inside the main function and passing it through the stack from then on instead of being a mutable global. The semantics of a global could be implemented on top of this i.e. MonadReader.

I guess I mean we all know singletons are bad, but that probably also means lazy_static and so on is bad.

xtal fucked around with this message at 02:29 on Apr 26, 2020

VikingofRock
Aug 24, 2008




Bruegels Fuckbooks posted:

The singleton pattern is completely automated if you use a dependency injection framework

Now you have two problems

E: to be less flippant, DI frameworks often make it hard to understand what is initializing what and when. IMO the solution to having global state is rarely to make that state more implicit.

VikingofRock fucked around with this message at 03:27 on Apr 26, 2020

NihilCredo
Jun 6, 2011

iram omni possibili modo preme:
plus una illa te diffamabit, quam multæ virtutes commendabunt

Yeah, a DI framework is just an indirection layer that sacrifices compile-time safety in exchange for reducing manual DI boilerplate. That's a tradeoff to be weighed very, very carefully.

Bruegels Fuckbooks posted:

The singleton pattern is completely automated if you use a dependency injection framework - there are cases where semantically, the singleton pattern works, but if you're writing classes with name "singleton" in them, you're probably making a mess. Letting your DI framework enforce the "singletonness" of a class works out a lot better for test-ability and refactoring.

The problems with the singleton pattern aren't really due to the implementation being complex or easy to screw up - as long as your language provides a decent mutex or other thread-safety mechanism, you can write a correct (generic) singleton just fine in like 20 lines of code, tops.

The fact that a DI framework happens to ship with a standard implementation and lets you write .AddSingleton() or @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) doesn't really address any of the issues people have with the pattern.

dwazegek
Feb 11, 2005

WE CAN USE THIS :byodood:
I kinda feel that DI singletons should have been called something else, as they (at least in my experience) have very little to do with the actual singleton design pattern.

In all the codebases I've worked on, almost all the stuff that gets registered as a singleton for DI is just a stateless class, that could be instantiated an arbitrary number of times, but there really is no need to ever have more than one. Stuff like validators, mappers, factories and the like. They could be given a scoped or transient lifestyle, and the application would work just fine. The only reason they are registered as singleton is to reduce some unnecessary overhead and so that they can be injected into other singletons.

Personally I've never encountered a use case for a "real" singleton. I've seen scenarios where you only need or want one instance, but never a scenario where literally only one instance should exist.

NihilCredo posted:

Yeah, a DI framework is just an indirection layer that sacrifices compile-time safety in exchange for reducing manual DI boilerplate. That's a tradeoff to be weighed very, very carefully.

Certain DI frameworks (like SimpleInjector) have a strict verification system, which at least makes it possible to perform unit tests that ensure that the application's configuration is correct, which makes weighing the tradeoff easier. Granted, it's not compile-time safety, but it can still be done as part of the build process.

leper khan
Dec 28, 2010
Honest to god thinks Half Life 2 is a bad game. But at least he likes Monster Hunter.

dwazegek posted:

I kinda feel that DI singletons should have been called something else, as they (at least in my experience) have very little to do with the actual singleton design pattern.

In all the codebases I've worked on, almost all the stuff that gets registered as a singleton for DI is just a stateless class, that could be instantiated an arbitrary number of times, but there really is no need to ever have more than one. Stuff like validators, mappers, factories and the like. They could be given a scoped or transient lifestyle, and the application would work just fine. The only reason they are registered as singleton is to reduce some unnecessary overhead and so that they can be injected into other singletons.

Personally I've never encountered a use case for a "real" singleton. I've seen scenarios where you only need or want one instance, but never a scenario where literally only one instance should exist.


Certain DI frameworks (like SimpleInjector) have a strict verification system, which at least makes it possible to perform unit tests that ensure that the application's configuration is correct, which makes weighing the tradeoff easier. Granted, it's not compile-time safety, but it can still be done as part of the build process.

I wish I had never seen or been forced to work on a project where all state is managed through singletons. Hearing the person behind that decision was leaving the org was the happiest day of the job.

Ralith
Jan 12, 2011

I see a ship in the harbor
I can and shall obey
But if it wasn't for your misfortune
I'd be a heavenly person today

xtal posted:

It's Rust's lazy_static, if it had to be wrapped in OOP. The same process is used more loosely in C. The equivalence is that the term is a global that's initialized on first usage, but always referenced as a global, and the memoization is transparent.

An alternative would be having the definition be inside the main function and passing it through the stack from then on instead of being a mutable global. The semantics of a global could be implemented on top of this i.e. MonadReader.

I guess I mean we all know singletons are bad, but that probably also means lazy_static and so on is bad.

I've only ever used or seen uses of lazy_static for constant, immutable, deterministic data tables that would have been consts if the language supported that.

Singletons are globals, full stop. As with any global, the problem is (if it's mutable) they make it much harder to test, refactor, and ensure encapsulation and independence of code.

qsvui
Aug 23, 2003
some crazy thing
You can do DI without a framework just fine

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

dwazegek posted:

Personally I've never encountered a use case for a "real" singleton. I've seen scenarios where you only need or want one instance, but never a scenario where literally only one instance should exist.

I've encountered a reasonable number. A connection pool for a given backend makes sense as a stateful singleton, for example.

Scoped instances are much more common, but you can really think of those as "a singleton in a given scope" (making global singletons essentially scoped instances who's scope is the entire application process).

Space Gopher
Jul 31, 2006

BLITHERING IDIOT AND HARDCORE DURIAN APOLOGIST. LET ME TELL YOU WHY THIS SHIT DON'T STINK EVEN THOUGH WE ALL KNOW IT DOES BECAUSE I'M SUPER CULTURED.

dwazegek posted:

Personally I've never encountered a use case for a "real" singleton. I've seen scenarios where you only need or want one instance, but never a scenario where literally only one instance should exist.

There's never going to be a case where you absolutely have to use the singleton pattern.

But, if you're really managing some kind of global shared state, it's a good way to enforce "there should only be one of these" in code. Global shared state is generally something you want to avoid, but if it's unavoidable then singletons are a reasonable way to do it.

For an example of something that probably should be more singleton-like, take a look at the HttpClient class in .NET. It keeps a connection pool, so a single instance should be reused as widely as possible - usually, a single instance of that object should persist for an entire application from startup to shutdown. The connections are an OS-level shared resource and can run out. HttpClient is marked as disposable (providing a cleanup method, basically), so that it can cleanly shut down connections when it's terminated. C# provides a language feature, using, that lets you easily instantiate a scoped disposable object, and guarantee its cleanup when execution leaves that scope.

You can probably guess what happens here - people write using (HttpClient httpClient = new HttpClient()) {/* some code */} all the time, scoped to short lifecycles (sometimes even individual HTTP requests). Their code works fine in testing, then falls over badly in production once it starts running a bunch of simultaneous connections. One clean way to handle this is to wrap that HttpClient object in a singleton. You can also do what Microsoft did and just say "hey, it says in the docs to not make more than one of these" - but people don't always read the docs like they should. Baking the pattern into the code makes it a lot harder to misuse things.

ultrafilter
Aug 23, 2007

It's okay if you have any questions.


Yeah, global singletons for resource management actually seems like a good general pattern.

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

qsvui posted:

You can do DI without a framework just fine

Once you have to worry about testing, you'll either implement your own DI framework inadvertantly, or you'll realize that you didn't actually need to inject that thing.

Steve French
Sep 8, 2003

Jabor posted:

I've encountered a reasonable number. A connection pool for a given backend makes sense as a stateful singleton, for example.

Scoped instances are much more common, but you can really think of those as "a singleton in a given scope" (making global singletons essentially scoped instances who's scope is the entire application process).

I've also encountered good reasons to have multiple connection pools for the same backend, on the other hand, so while this may be a great default it maybe shouldn't be an enforced singleton

Carbon dioxide
Oct 9, 2012

https://toni.technetium.be/hacker/pragma.htm

The ANSI C standard declares #pragma as implementation-defined. [...] #pragma met with some initial resistancee from a gcc implementor, who took the "implementation-defined" effect very literally. [...] In gcc version 1.34 [...] "#pragma first attempts to run the game "rogue"; if that fails, it tries to run the game "hack"; if that fails, it tries to run GNU Emacs displaying Tower Of Hanoi; if that fails, it reports a fatal error. In any case, preprocessing does not continue."

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Carbon dioxide posted:

https://toni.technetium.be/hacker/pragma.htm

The ANSI C standard declares #pragma as implementation-defined. [...] #pragma met with some initial resistancee from a gcc implementor, who took the "implementation-defined" effect very literally. [...] In gcc version 1.34 [...] "#pragma first attempts to run the game "rogue"; if that fails, it tries to run the game "hack"; if that fails, it tries to run GNU Emacs displaying Tower Of Hanoi; if that fails, it reports a fatal error. In any case, preprocessing does not continue."

"Implementation-defined" is a lovely way of defining a standard for observable behavior. "Implementation is free to do what it likes, but must document its choice and stick to it?" gently caress you, I thought a standard was supposed to tell me what to do, not have me make up a standard.

1337JiveTurkey
Feb 17, 2005

Singletons are also helpful with hierarchical logging where there’s one root and multiple children that all implement the same interface. Related to DI a singleton doesn’t even need to be globally single but can also be a single instance per user or per whatever, just easily grabbed as “the instance.”

Ralith
Jan 12, 2011

I see a ship in the harbor
I can and shall obey
But if it wasn't for your misfortune
I'd be a heavenly person today

Bruegels Fuckbooks posted:

"Implementation-defined" is a lovely way of defining a standard for observable behavior.

Well, yeah, because defining a standard for such a case is exactly the thing they're trying not to do.

Tei
Feb 19, 2011

Zopotantor posted:

Nah, a Java programmer would have made it a loving Singleton.

Java programmers where not invented yet. And the Gang of Four where only a group of unruly childrens vandalizing people gardens in (noun here).

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

Ralith posted:

Well, yeah, because defining a standard for such a case is exactly the thing they're trying not to do.

Pretty much. This is the way to let your compiler, which you paid hundreds or thousands of 1980s dollars for, do whatever fancy tricks they've added.

more falafel please
Feb 26, 2005

forums poster

I just wish compilers would standardize #pragma optimization settings, since all the major ones support them, so for crossplatform projects you just end up writing a platform-defined macro that looks dumb. They largely all standardized on #pragma once, there's precedent.

qsvui
Aug 23, 2003
some crazy thing
Standardizing struct packing would also be nice

Tei
Feb 19, 2011

more falafel please posted:

I just wish compilers would standardize #pragma optimization settings, since all the major ones support them, so for crossplatform projects you just end up writing a platform-defined macro that looks dumb. They largely all standardized on #pragma once, there's precedent.

I am generally against everything in general. But I don't see how this would hurt. Worst thing that can happen is a compiler ignoring these pragmas.

redleader
Aug 18, 2005

Engage according to operational parameters
i'm against anything that makes c more predictable, because making things easier will make it more likely that people will start to think the compilers are predictable and reasonable and not capricious, petty gods

Tei
Feb 19, 2011

Somebody high up in Google decided that the only user case worth supporting on Chrome is somebody filling the details of the credit card, or login in a form.

A victim of this has been autocomplete=off, disabling autocomplete.

Since them, every form ever is threaten like a login form, so if you are editing a user, and changes random data, the browser may automatically update this field or other data. And have his own widget on top of existing widget for autocompletion, for things has ridiculous has datepickers.

https://bugs.chromium.org/p/chromiu...20OS%20Modified

The war for this continue, the old bug for this was flagged wontfix, so people created a new bug.

QuarkJets
Sep 8, 2008

redleader posted:

i'm against anything that makes c more predictable, because making things easier will make it more likely that people will start to think the compilers are predictable and reasonable and not capricious, petty gods

Why would you want to mislead people like that

Tei
Feb 19, 2011

redleader posted:

i'm against anything that makes c more predictable, because making things easier will make it more likely that people will start to think the compilers are predictable and reasonable and not capricious, petty gods

I have never run on a problem that has made me think compilers are irrational.

Sometimes you make a mistake, and that throwns the syntax analiser out of wack, ... in C the lack of a ";" or a closing ")" or "}".

But once you have a bit of experience with the compiler, you learn to recognice these moments. With modern IDE's and syntax coloring, these problems are easy to solve, many editors highlight the couple of a ). or have a static analizer that already tell you theres a odd number of closing pairs.

* taps The Dragoon Book with one paw *. compilers are your friend

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Tei posted:

Somebody high up in Google decided that the only user case worth supporting on Chrome is somebody filling the details of the credit card, or login in a form.

A victim of this has been autocomplete=off, disabling autocomplete.

Since them, every form ever is threaten like a login form, so if you are editing a user, and changes random data, the browser may automatically update this field or other data. And have his own widget on top of existing widget for autocompletion, for things has ridiculous has datepickers.

https://bugs.chromium.org/p/chromiu...20OS%20Modified

The war for this continue, the old bug for this was flagged wontfix, so people created a new bug.

autocomplete="off" is overused and should be ignored when the form is asking for an email address :colbert:

Tei
Feb 19, 2011

Munkeymon posted:

autocomplete="off" is overused and should be ignored when the form is asking for an email address :colbert:

What about /form/user/31, you want the edit details of the user 31 to be autofilled with the details of the admin when he is editing the user profile?

LOOK I AM A TURTLE
May 22, 2003

"I'm actually a tortoise."
Grimey Drawer

Tei posted:

Somebody high up in Google decided that the only user case worth supporting on Chrome is somebody filling the details of the credit card, or login in a form.

A victim of this has been autocomplete=off, disabling autocomplete.

Since them, every form ever is threaten like a login form, so if you are editing a user, and changes random data, the browser may automatically update this field or other data. And have his own widget on top of existing widget for autocompletion, for things has ridiculous has datepickers.

https://bugs.chromium.org/p/chromiu...20OS%20Modified

The war for this continue, the old bug for this was flagged wontfix, so people created a new bug.

A guy from that ticket posted:

Here are some serious concerns: In creating a test form, Chrome decided to show the ugly popup autofill with the test data that my team used. Imagine our surprise when completley unrelated terms like DILDO or BUTTHEAD (the nicest of the dozen or so derogatory test inputs entered). became prominent autofill suggestions during our presentation. We were trying to demonstrate a new way to help users complete email addresses by using the data-list option with dynamically updated options (i.e. no need to type @gmail.com it becomes a suggestion in the autofill) Instead, I type B and Butthead is prominently suggested. Thanks Google! It nearly cost me my job and it underscores four big issues that seriously need to be addressed.

Thanks for the dildos and buttheads Google!

Ola
Jul 19, 2004

Always present in a clean browser. With all the crap on my bookmark toolbar, form autocomplete, youtube suggestions etc, presenting something using my day to day browser would be like having a meeting in a dorm room with laundry and empty takeout boxes everywhere. The only thing you need to set is to switch off youtube's "autoplay up next" which is somehow rendered in a colorspace completely invisible to people over 40.

Ralith
Jan 12, 2011

I see a ship in the harbor
I can and shall obey
But if it wasn't for your misfortune
I'd be a heavenly person today

Tei posted:

I have never run on a problem that has made me think compilers are irrational.

Sometimes you make a mistake, and that throwns the syntax analiser out of wack, ... in C the lack of a ";" or a closing ")" or "}".

But once you have a bit of experience with the compiler, you learn to recognice these moments. With modern IDE's and syntax coloring, these problems are easy to solve, many editors highlight the couple of a ). or have a static analizer that already tell you theres a odd number of closing pairs.

* taps The Dragoon Book with one paw *. compilers are your friend

I don't think he's talking about trivial syntax errors.

Adbot
ADBOT LOVES YOU

taqueso
Mar 8, 2004


:911:
:wookie: :thermidor: :wookie:
:dehumanize:

:pirate::hf::tinfoil:

It's the spec that is bad


Compilers too though, they are software after all

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply