Why people dislike global variables so much while I find them so convenient?

max haughton maxhaton at gmail.com
Thu Jan 27 02:49:26 UTC 2022


On Thursday, 27 January 2022 at 01:01:56 UTC, H. S. Teoh wrote:
> On Thu, Jan 27, 2022 at 12:45:20AM +0000, forkit via 
> Digitalmars-d wrote: [...]
>> I just counted the globals in my GUI IDE (that I developed 
>> with C#/Winforms.
>> 
>> 34
>> 
>> many set deafault, that can later be modified during function 
>> calls, depending on needs at the time.
>> 
>> Without globals, I'd never have bothered ;-)
> [...]
>
> Some of your globals are actually global values, like:
>
>> string clang_exe = "clang.exe";
>> bool Is64Bit;
>> bool vs2019_available = false;
>> bool vs2015_available = false;
>> string dcompiler_mars = "dmd.exe";
>> string dcompiler_llvm = "ldc2.exe";
>
> These I wouldn't be ashamed of declaring as globals, since they 
> ARE globals (in the sense of describing the global environment 
> the program will run in).  You can usually tell these from 
> other globals by whether or not you can make them immutable 
> (though sometimes you may want to keep them mutable if, e.g., 
> you're picking them up from the runtime environment or via 
> program options -- but the idea being that once they're 
> initialized they're effectively immutable).
>
> Others, however, I'd stick into a configuration struct or as 
> member fields in your program's main class, such as:
>
>> bool new_compile_needed = true;
>> public bool new_record_mode = false;
>> System.Drawing.Color MyBackColor = Color.Black;
>> System.Drawing.Color MyForeColor = Color.Lavender;
>
>
> T

The distinction is basically between global state (i.e. things 
that are mutated often, like "pointer to current item") and 
globals that are *stated* e.g. "Is logging turned on". The latter 
is mostly fine with the caveat that it can be indicative of bad 
architecture (e.g. multiple instances of something like an 
interpreter is often impossible with any global state at all), 
the former is extremely bad and can absolutely ruin a program. If 
you have lots of global state (or even local state whose 
structure isn't natural) you are doing something wrong.


More information about the Digitalmars-d mailing list