lately I'm having the feeling that instances variables have the same problems of global variables, I googled about this and found this old article that more or less describes the potential problem i'm seeing.
What good practices do you use to avoid that the same problems of global variables affect instance variables or class variables?
Global variables are not technically allowed in Java. A global variable is one declared at the start of the code and is accessible to all parts of the program. Since Java is object-oriented, everything is part of a class. ... A static variable can be declared, which can be available to all instances of a class.
The term "instance variable" is another name for non-static field. The term "class variable" is another name for static field. A local variable stores temporary state; it is declared inside a method. A variable declared within the opening and closing parenthesis of a method is called a parameter.
In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the global environment or global state.
Class Variables vs Instance VariablesClass variables are associated with the class. Instance variables are associated with objects. Class variables create one copy for all objects. Instance variables create separate copy for each object.
Classes are much smaller than global structure so the impact of an instance variable is much smaller. By keeping small class sizes and adhering closely to the single responsibility principle, much of the downside of a global variable is averted. If the instance variable is created from a passed in parameter then I often make that parameter required in the constructor making the dependency explicit. Also the instance variable is encapsulated well, never being directly modified outside of the instance's methods making it very easy to determine where the instance variable is modified. Finally the instance variable must make sense to the class as a whole or must be private.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With