Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Considering I have a for loop in a method of a class. Should the incremented variable be declared as member of the class, or should it be declared in the method it uses it(or even in the for loop, directly)? While declaring it inside the method seems easier and cleaner, doesn't declaring it at the start of the class makes you have more control over it? Something like declaring it int var_used_for_loop_in_method_x. What is good programming practice?

Note that I'm not asking specifically for the for loop. I am asking if we should try to put most variables as class members as much as possible or not.

share|improve this question
1  
Could you write some code examples that demonstrate the different styles? Also, which language - different languages have different idioms and constraints to them. Also - please read Where do you declare variables? which may deal with specific cases. –  MichaelT 3 hours ago
add comment

1 Answer

Rule of thumb: variables should always be in, or as close as possible to, the scope where they are needed. Another way to phrase it is that variables should be enclosed inside the context in which they make sense and are actually useful.

Most often you will want to declare your incrementing variable along with the for statement. Sometimes you will declare it a bit higher in the hierarchy because you need to know how many occurences you looped through or at which point the loop was interrupted.

In almost all scenarios, having a loop increment variable declared as a class field is a bad idea. It won't give you any kind of additional "control"; if anything, it will only pollute your class and make it harder to figure out from an outsider's perspective. Plus, if you inadvertly use it in more than one loop, it may even break your code.

share|improve this answer
4  
To advance on this: variables should have the smallest possible scope that gets the job done. That's why index variables are declared in the for loop. It is also related to the rule of thumb: initialize things as late as possible. By implication then, since you want to have variables initialized, they should be declared as late as possible. –  BobDalgleish 3 hours ago
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.