How to create global variables
Global variables are variables that are accessible from anywhere in the application. In other words, their scope is the entire application. To create such a variable in Java, you need to create a public static variable in a public class:public class Example {
public static int a;
public static int b;
public static String str;
}
The variables a
, b
and str
- have become global. We can access them directly from other classes inside the application:
public class GlobalVarsDemo {
public static void main(String[] args) {
Example.a = 4;
Example.b = 5;
Example.str = "Global String variable value";
System.out.println(Example.a);
System.out.println(Example.b);
System.out.println(Example.str);
}
}
If we run the method main
, we will see the following output:
4
5
Global String variable value
Global variables can be divided into 2 types:
- variables that can be edited;
- variables that can only be read.
final
and assign a value to it when defining the variable:
public class Constants {
public static final double PI = 3.1415926535897932384626433832795;
public static final String HELLO_WORLD_STR = "Hello, World!";
}
According to the Java naming convention, all constants must be named in upper case, separating words with an underscore character. So, we have created constants, and now we will not be able to change their values: However, we can read their values:
public class HelloWorld {
public static void main(String[] args) {
System.out.println(Constants.HELLO_WORLD_STR);
}
}
Conclusion:
Hello, World!
public class ConstantsDemo {
public static void main(String[] args) {
double r = 10;
String message = String.format("Площадь круга с радиусом %f=%f", r, getCircleSquare(r));
System.out.println(message);
}
static double getCircleSquare(double r) {
return Constants.PI * r * r;
}
}
Conclusion:
Площадь круга с радиусом 10,000000=314,159265
Should you use global variables?
There are many articles on the Internet, the main message of which is this: global variables are evil, bad and terrible. Is it really? Let's try to give the pros and cons of global variables so that everyone can draw their own conclusion. Let's start with the cons. Let's imagine an application that has a class with global variables that can be read and edited. Over time, the number of classes in the project, the number of global variables and methods that use global variables, or in other words, depend on them, grows. Over time, each global variable is read in different parts of the system for different purposes. In different parts of the system, the value of a variable can be updated. The overall picture of the world of this application becomes significantly more complicated, and this leads to the following disadvantages :- Reduced readability and increased difficulty in understanding code.
- Increased complexity of code maintenance.
- To change one global variable, it is necessary to analyze the entire code so as not to set the variable to a value that is invalid for other parts of the system.
- Increase in errors that are very difficult to debug.
Let's imagine a global variable, an array of objects. In one part of the system, for example, strings are expected in this array, and in another part of the system, someone decided to use floating point numbers. It’s unlikely that anyone would want to understand this.
- The variable names may be the same if you use global variables in your code, as well as some libraries that, in turn, also use global variables. This can lead to errors both on the side of your application and on the side of the library you are using.
- Increases connectivity between different parts of the system that use global variables. On the contrary, you should strive for loose coupling of the code. It's better to have many small subsystems loosely connected to each other than to have one hefty thing. Because it is easier for the brain to deal with several simple things than with one too complex and confusing thing.
- Writing unit tests becomes more difficult because the test does not know which global variables are needed and how they need to be initialized.
- In multithreaded applications, the use of global variables by different threads leads to an increase in errors that are difficult to debug and to an increase in project complexity. Because of this, it is necessary to configure access to such variables more correctly, equipping them with synchronizations and locks. This may lead to short circuits in the future. For example, thread A has locked variable X for its work, and thread B has locked variable Y for its work, and thread A now needs variable Y, and thread B needs variable X. As a result, the program will freeze.
- In small projects, global variables are the simplest thing to make the project work.
- Sometimes the fear of using global variables leads to even more complexity in the project. Then programmers start creating singletons and resorting to other design patterns.
- In programming, you often need to rely on some immutable values.
The most reasonable thing is to write such values as a constant, because only constants guarantee that the value of a variable will not change over time. Such constants can be found all the time (
Integer.MAX_VALUE
,Integer.MIN_VALUE
,Boolean.TRUE
,Collections.EMPTY_LIST
etc.). But programming is not limited to using standard libraries. It often happens that you need to write some kind of unique logic, which will need to rely on your own unique constants. That's why sometimes using constants (read-only global variables) really makes life easier.
- Everything that a novice developer writes is essentially a small project. And using global variables in his projects will teach him to use global variables everywhere.
- It is better to first learn to do without “forbidden tricks”. And with experience, the understanding of when it is appropriate to use such techniques will come on its own.
GO TO FULL VERSION