Refactor Match Loop To Usage

When most of the code in a "for" loop uses an offset to the loop index, rather than the loop index itself, then maybe the for loop should be adjusted to loop over the range of values that the code needs, rather than computing some other value at each point of usage.


Example:

Starting here:

   For i = 1 to max
      array[i-1] = otherarray[i-1] + factor * (i-1)
      ' other stuff using "i-1" a lot...
   Next i

ExtractLocalVariable? Refactoring:
   For i = 1 to max
      j = i - 1
      array[j] = otherarray[j] + factor * (j)
      ' other stuff using "j" a lot...
   Next i

Then ajust the loop range to eliminate the computation:
   For j = 0 to max-1
      array[j] = otherarray[j] + factor * (j)
      ' other stuff using "j" a lot...
   Next j


Related discussion: InternalLoopExitsAreOk (or NOT ;-)


See also: RenumberIndexVariable


ContributorsList: JeffGrigg


CategoryRefactoring/RefactoringLanguage UseEnumerationsInsteadOfForLoops


EditText of this page (last edited January 28, 2009) or FindPage with title or text search