Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are the instance variables the new global variables?

Tags:

oop

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?

like image 637
javier Avatar asked Jul 14 '12 00:07

javier


People also ask

Is instance variable global in Java?

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.

What is another name for instance variables?

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.

Which of the variables are global variables?

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.

Are instances and variables the same?

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.


1 Answers

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.

like image 142
Peter Smith Avatar answered Oct 23 '22 00:10

Peter Smith