Reputation: 535
I have a complicated condition inside else
block inside a loop. So I decided to form some new variables to simplify this condition. Where should I declare these variables?
//here 1
for (...) {
//here 2
if(...) {
} else {
//here 3
if (cond1 && cond2){}
}
}
Upvotes: 0
Views: 106
Reputation: 335
Probably the best solution is this :
boolean cond1,cond2 = false;
for (...) {
//here 2
if(...) {
} else {
cond1 = ...
cond2 = ...
if (cond1 && cond2){}
}
}
this allows you to allocate no memory for variables at each iteration.
Upvotes: 1
Reputation: 1741
You should declare variables where they are needed, so in this case probably in here 3
.
Upvotes: 2
Reputation: 178521
You should declare variables closest as possible to their usages, and in the "smallest" scope possible.
In your example, if cond1,cond2 are used ONLY when you write them in the sample, they should be declared in here 3
.
Upvotes: 4