2

When declare Java variables
Why its recommended to use the narrowest scope as possible
Like that

Its recommended

if (x>3) {
double d = someCalculation();
// ......
System.out.println("...");
} else {
// No use of d
System.out.println("...");
}

Its NOT recommended

double d = someCalculation();
if (x>3) {          
// ......
System.out.println("...");
} else {
// No use of d
System.out.println("...");
}
Ahmed Nabil
  • 17,392
  • 11
  • 61
  • 88

6 Answers6

4

Easier to read, maintain, and demonstrate the program is correct.

Anyway, this answer covers it well.

Also try searching for "limiting variable scope" (sample hit)

Community
  • 1
  • 1
djechlin
  • 59,258
  • 35
  • 162
  • 290
4

Once a scope executed all the variables declared within the scope are eligible for garbage collection, so you need to have to carry those variables if it is no longer needed.

In your case as soon as the if(...) {...} block is executed d is eligible for GC

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

Because when you declares a variable, this is created and reserves a space in the memory. Even if you don't use this variable, the space is created. Declare the variable only if it's needed.

Xean
  • 25
  • 1
  • 1
  • 5
0

Because the scope in which it is needed it necessarily must be declared, whereas where not needed it's potentially likely an irrelevant variable. The answer to this lies in the question: why would you just leave things lying around in places they have nothing to do with? You generally don't, I hope - at least not since you were a teenager.

Consider all the clothes on the floor back in the day, no one mom knowing which was clean and which dirty. Does she wash them all, or leave them all, or what? So it is with memory management in such technologies. What's being used? What can I move around? What can I dispose of? etc.

Maintaining clean scopes and suchlike in these cases has a number of benefits, other than this just being a natural thing to do. Pieces of code in scope can be seen as 'units of work' in some case, and it can also protect from data conflicts if a variable (name+type) is reused.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
0

For the same exact reason you don't post your phone number, emails address and citizenship ID number of whatever country you are from on your stackoverflow profile just to get this answer. You manage variables in the most minimalist exposure to prevent cluttering, improve readiblity, and reduce potential confusion.

amphibient
  • 29,770
  • 54
  • 146
  • 240
-1

Also in your example, you will perform someCalculation() whether it is needed or not. Not very efficient.

Chris
  • 923
  • 1
  • 8
  • 11