Why are global variables bad, in a single threaded, non-os, embedded application

后端 未结 13 1586
既然无缘
既然无缘 2020-12-01 05:20

Most of the objections I see to using global variables make sense since they refer to issues of multiple threads, thread safety, etc.

But in a small, single threaded

13条回答
  •  有刺的猬
    2020-12-01 06:07

    Here is a good article that gives reason Why global variables are Bad

    Why Global Variables Should Be Avoided When Unnecessary?

    Non-locality -- Source code is easiest to understand when the scope of its individual elements are 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 Constraint Checking -- A global variable can be get or set by any part of the program, and any rules regarding its use can be easily broken or forgotten.

    Implicit coupling -- A program with many global variables often has tight couplings between some of those variables, and couplings between variables and functions. Grouping coupled items into cohesive units usually leads to better programs.

    Memory allocation issues -- Some environments have memory allocation schemes that make allocation of globals tricky. This is especially true in languages where "constructors" have side-effects other than allocation (because, in that case, you can express unsafe situations where two globals mutually depend on one another). Also, when dynamically linking modules, it can be unclear whether different libraries have their own instances of globals or whether the globals are shared.

    Testing and Confinement - source that utilizes globals is somewhat more difficult to test because one cannot readily set up a 'clean' environment between runs. More generally, source that utilizes global services of any sort that aren't explicitly provided to that source is difficult to test for the same reason.

    Adding globals is really easy. It's easy to get in the habit of declaring them. It is much faster than thinking of a good design.

    Global variables are not as bad as you may think, they just should be avoided whenever unnecessary. Global variables can have good use for a variable that would be used thoughout the program,making sure you keep in mind that you always have to keep track of where that variable takes changes; but for variables that tend to be only used within limited parts of the program is good reason to avoid having it global.

提交回复
热议问题