Why people dislike global variables so much while I find them so convenient?
Ola Fosheim Grøstad
ola.fosheim.grostad at gmail.com
Tue Jan 25 10:22:17 UTC 2022
On Tuesday, 25 January 2022 at 09:53:25 UTC, rempas wrote:
> So can someone make examples about how global variables can
> mess me up. I know that probably everyone here has more
> personal experience than me so I really want to learn why
> global variables are considered so harmful.
Harder to debug. Harder to reason about as your program grows in
size. Harder to scale your program to higher degree of
concurrency. But there is a place and room for everything.
If you use globals you should keep them local to one object-file
and limit access to accessor functions to make it easier to debug
If you only use globals because you want to have fewer parameters
then the common approach is to instead use a context-object and
pass that as single parameter.
Unfortunately, D made the mistake of making thread-local the
default, and claimed this was a great improvement. Thread local
globals are basically something you only want to use in runtime
and framework "kernel" like code. That gets you an additional
layer of issues, including performance.
If you use globals, make sure you either mark them appropriately
so that you don't get thread local globals.
More information about the Digitalmars-d