Why people dislike global variables so much while I find them so convenient?
rempas at tutanota.com
Wed Jan 26 08:46:04 UTC 2022
On Tuesday, 25 January 2022 at 14:28:24 UTC, H. S. Teoh wrote:
> [ The problem with global variables ... it makes debugging an
> extremely unpleasant experience. ]
Yeah, it makes sense. You need to be sure that your functions
will be called in a specific order hence why this can be
dangerous in libraries.
> [ Another problem with global variables is that ... just pass
> the 2nd connection and you're done. ]
Yeah, you are right and this is why I asked for examples because
I haven't worked with everything and I just don't know. I will
also have a problem with my project when I add multi-thread
support so I will change it's structure now that it is smaller.
> Whenever you have multiple shared parameters between a bunch of
> functions, that's a sign that they probably should be member
> functions of a common struct or class. The shared parameters
> should be in the struct, then you don't have to explicitly pass
> them around, you just add another function to the struct and
> they gets passed implicitly for you.
This actually makes total sense. I will change my program to do
that instead! Thanks!
> Either group your parameters in a single struct, or make your
> functions members of the struct. Then all you have to do is add
> another field to your struct and you're done. No tedium.
Actually, I was wondering something. Maybe I should read the
whole reference first but I'll just ask in case you know. Is
there a way to just declare a struct/class method and define it
outside the struct/class like in C++? It will be very annoying to
have all my functions be in the same file. The first method seems
better to me.
> Using a struct/class also takes care of the instancing problem:
> if one day you suddenly need a different set of parameters, you
> just create a different instance of your struct and everything
> Just Works(tm). If they were global variables, then there can
> only be one instance of every variable, and you're stuck up the
> creek without a paddle.
Yeah, I didn't thought about that before. That's why I'm glad
people always try to help! Thanks a lot for your time!
More information about the Digitalmars-d