The global variable anti-pattern is detected for global non-static and non-const variables which are exposed using “extern” keyword. This anti-pattern is only applicable to C/C++.
Impact
- As Global variables can be read and modified from multiple parts of the program, it is difficult to restrict access making them prone to bugs.
- Global variables add implicit coupling between the variables and user functions/ modules thus impacting cohesiveness.
- If multiple threads access the same Global variable, it might lead to concurrency issues if synchronization is not handled correctly.
- Source code entities are easiest to understand when their scope is limited. Global variables can be read and modified from multiple parts of the program making it difficult to understand and maintain.
Characteristics
- The variable is a Globally exposed variable
- The variable is non-static and non-const
- The variable is exposed using “extern” keyword.
Example(s)
// header.h / file1.c int g_intVar = 10; // Define global variable “g_intVar” // file2.c extern int g_intVar; // Used global variable defined in file1.c int fun_a(){ if(g_intVar < 20){ g_intVar = 20; // Modified global variable } } // file3.c extern int g_intVar; // Function takes int parameter as reference int fun_b(int & outVar) { // Some condition …. outVar = 50; return 0; } int fun_c(){ int ret = fun_b(g_intVar); // Passing global variable leading to its modifications }
Guidelines
- Pass the variable as a parameter instead of using the Global variable.
- Use getter and setter functions to get and set the variable instead of making it global. This will also help in adding more constraints when the setter is called.
- If the variable is not expected to be changed, make it “const”.