Why global variables should be avoided when unnecessary
Nonlocality . Source code is easiest to understand when the volume of its individual elements is limited. Global variables can be read or modified by any part of the program, making it difficult to remember or reason about every possible use.
No access control or restriction checking . A global variable can be obtained or set by any part of the program, and any rules regarding its use can be easily broken or forgotten. (In other words, get / set Accessors are usually preferable to direct access to data, and this is even more so for global data.) In addition, the lack of access control significantly impedes security in situations where you may want to run untrusted code (for example, working with third-party ones) plugins).
Implicit link . A program with many global variables often has tight connections between some of these variables and couplings between variables and functions. Grouping related items into connected units usually leads to better programs.
Concurrency returns - if global global objects can be accessed by multiple threads of execution, synchronization is necessary (and too often neglected). When dynamically linking modules to global ones, a compiled system can be unsafe, even if two independent modules tested in dozens of different contexts were safe.
Namespace pollution . Global names are universally available. You can unconsciously end up using global when you think you are using local (spelling or forgetting to declare local) or vice versa. Also, if you need to bind modules, the same global variable name, if you're lucky, you'll get an error link. If you're out of luck, the linker will simply consider all uses with the same name as the same object.
Memory allocation problems - Some environments have memory allocation schemes that make global allocation tricks. This is especially true in languages where "constructors" have side effects other than distribution (because in this case you can express unsafe situations where two global characters are mutually dependent on each other). In addition, when dynamically linking modules, it may not be clear whether different libraries have their own instances of global or shared global ones.
Testing and confinement - a source that uses global variables, is a little harder to verify because you cannot easily set up a "clean" environment between runs. More generally, a source that uses global services of any type (for example, reading and writing files or databases) that are not explicitly provided to this source is difficult to verify for the same reason. For communication systems, the ability to test system invariants may require the launch of more than one “copy” of the system at a time, which greatly complicates any use of shared services - including global memory - that are not intended to be shared as part of the test.