Why people dislike global variables so much while I find them so convenient?
rempas at tutanota.com
Wed Jan 26 09:10:58 UTC 2022
On Tuesday, 25 January 2022 at 14:29:32 UTC, Steven Schveighoffer
> That's not the reason. Global variables are hard to control and
> review. That is, if a variable is global, how do you know it's
> not misused? The point of not using global variables is to
> reduce the surface area of the program that needs review to
> ensure it's correctly used.
Yeah, I understand know how this can be very important with
bigger and more complex apps where a lot of developers will work
or with Library APIs.
> In some cases, they make sense, and in those cases, I'd
> recommend at least guarding the direct access to the variable
> through properties so you can control how it's used.
What do you mean "properties"? I suppose not struct/class
> 1. Declare the variables in a function, then run your
> algorithms inside inner functions. They all now have access to
> the variable. I'm surprised at how many complex problems and
> APIs become super-straightforward when you start using local
> functions (even templated ones).
That's actually a really great way of doing it but it will be a
mess if you have the huge functions that I do. This will work
great with small algorithms. Or you could use string enums to
insert code in place. A lot of things to consider!
> 2. Enclose the data and methods in a struct, even if that
> struct is a struct inside a function. This is a necessity if
> you have mutually recursive functions, since a local function
> cannot call another local function that hasn't been defined yet.
This is what I'll probably do. Not only because of the problem
you mentioned but because it will allow my to use functions in
separate files like I normally would!
Thanks a lot for your time man!
More information about the Digitalmars-d