Stripies
Stripies

Reputation: 1267

Multiple Objects vs Changing One Object

I saw something today talking about this:

aClass something;
while (condition) {
    something = new aClass();
    ...
}
while (condition) {
    aClass something = new aClass();
    ...
}

It said you should use the second one rather than the first. Is this true, and if so, why?

Upvotes: 1

Views: 67

Answers (3)

Acidic
Acidic

Reputation: 6282

The second method keeps the something variable only in the scope of that specific loop iteration.
If you want to use the object outside the loop and / or keep the changes saved between iterations then you must use the first method.

Also, the second method doesn't define multiple variables, the compiler will usually optimize it in a way that makes sure only one variable is defined.

Upvotes: 1

Bill the Lizard
Bill the Lizard

Reputation: 405875

You should use the second example unless you need to use the object after the while loop is complete. If you don't need the variable in the outer scope it's better to declare it in the narrowest scope where it will be used (inside the loop). This simplifies the code for maintenance programmers who have to make sense of it.

Upvotes: 1

SLaks
SLaks

Reputation: 887657

Your first example leaks a useless variable into the outer scope.

Upvotes: 4

Related Questions