patternMinor
Is it a bad programming practice to declare variable in a loop?
Viewed 0 times
practiceprogrammingloopbaddeclarevariable
Problem
Today, I came across a code example like the following:
Once a variable goes in scope in VB6 and/or VBA, it stays in scope throughout the procedure.
So, is it a bad programming practice to declare a variable in a loop? Is it better to declare myString either at the top of the procedure or, at the very least, above the FOR LOOP?
Option Explicit
Sub MySub()
Dim iCount As Integer
For iCount = 0 To 100
Debug.Print "Arbitrary Code Here"
If iCount Mod 2 = 0 Then
Dim myString As String 'This is the line I'm curious about
myString = iCount
Debug.Print myString
End If
Next iCount
End SubOnce a variable goes in scope in VB6 and/or VBA, it stays in scope throughout the procedure.
So, is it a bad programming practice to declare a variable in a loop? Is it better to declare myString either at the top of the procedure or, at the very least, above the FOR LOOP?
Solution
There are a few things to consider here. First we have to consider if the position will matter to the compiler, which depends on the language. VB6 will scope that variable to the function (or sub in this case), so it doesn't matter too much there. In VB.NET, the variable will be scoped to the containing block (in this case the loop), so declaring inside of the loop would let us reuse that same variable name in some other block.
In terms of maintainability, there are two good reasons to put the declaration as close as possible to the first use of the variable. One, it improves readability. Two, it simplifies future refactoring -- imagine that you wanted to move that loop to its own function, that's easier if the variable is right there with the loop.
short answer: In VB6 I think it's best to declare just before the loop. This is mostly so that nobody thinks that the variable will be re-initialized every time the loop runs.
In terms of maintainability, there are two good reasons to put the declaration as close as possible to the first use of the variable. One, it improves readability. Two, it simplifies future refactoring -- imagine that you wanted to move that loop to its own function, that's easier if the variable is right there with the loop.
short answer: In VB6 I think it's best to declare just before the loop. This is mostly so that nobody thinks that the variable will be re-initialized every time the loop runs.
Context
StackExchange Code Review Q#2496, answer score: 8
Revisions (0)
No revisions yet.