Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of Global variables

Tags:

java

variables

Why is it that when I read others code I frequently see extensive use of "Global variables"?

For instance in Java code:

public class SomeClass {
   Button btn1;
   private void someMethod() {
       btn = new Button();
   }
}

btn1 is declared as "global" and a "convenient" variable to be used as easy access throughout the class. But when there is no modifier on it, it defaults to default access in Java.

Could this be a security risk? Why don't people declare them with private modifier right away if they are only planning to use them in only one specific class?

like image 274
Irina Avatar asked Feb 01 '11 14:02

Irina


People also ask

What is the use of global variable 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. The intent is to protect data from being changed. A static variable can be declared, which can be available to all instances of a class.

What is a use of global and local variable?

A global variable is a variable that is accessible globally. A local variable is one that is only accessible to the current scope, such as temporary variables used in a single function definition.

Is it good practice to use global variables?

Using global variables causes very tight coupling of code. Using global variables causes namespace pollution. This may lead to unnecessarily reassigning a global value. Testing in programs using global variables can be a huge pain as it is difficult to decouple them when testing.

What is the use of global variable in Python?

In Python, global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.


2 Answers

It is no global variable (does such a thing even exist in Java? I guess it depends on one's definition of global). It is still a class member.

The default visibility is package-private, so the variable is not public but can be accessed by other classes in the same package.

Normally one should strive for the "best" data encapsulation but there might be uses cases where this is appropriate.

like image 119
Felix Kling Avatar answered Sep 24 '22 21:09

Felix Kling


  1. btn1 is not a global variable. it is an instance variable of the class
  2. if no access modifier is specified, then it defaults to "package" level access i.e. btn1 is accessible to all the classes which belong to the same package as SomeClass
  3. if SomeClass is just a data holder and immutable (no setters etc) then this is perfectly OK.
  4. It is always better to be as much more restrictive as possible when it comes to the instance variables.
like image 42
Aravind Yarram Avatar answered Sep 26 '22 21:09

Aravind Yarram