Common sense seems to be that usage of global variables is bad, in particular if they are used as real variables (i.e. changing state; e.g. Why is Global State so Evil?).

How does it come then, that virtually any language I've used so far implements them nonetheless, especially the modern fourth generation (4GL) languages like python or perl?

Do there exist procedural languages without global variables. If not, would it be possible to create one completely without the concept of global rewritable state?

有帮助吗?

解决方案

Your assumption that global variables are used only for state is incorrect. In (probably) most interpreted languages, for example, namespaces are used to communicate interfaces. Since in many of these languages interfaces (enumerations, functions, classes) are just variables, then without global variables there will be no global interfaces.

In addition, some of the programmers out there work in constrained environment such as embedded systems and real real-time applications. In those environments where efficiency is above all, one tends to avoid deep stacks and heavy heaps. In those environments, communicating over global variables is often the most efficient option.

Note that from the theoretical standpoint there cannot be a program without some sort of global variables. After all, any program has to generate some output, and the output device is a global handle. Same goes for all other system interfaces such as the time, environment variables, etc. Having access to these variables only through getters and setters doesn't make them less global, only less visible.

A programming language is not supposed to inflict algorithmic censorship. It is a tool, and it is up to the programmer to use this tool in a right way.

其他提示

Newspeak has no global variables. And in fact no global and/or static state at all. It also doesn't have a global namespace (the designer considers a global namespace to be equivalent to global and/or static state).

许可以下: CC-BY-SA归因
scroll top