-
Notifications
You must be signed in to change notification settings - Fork 314
Description
What
Let's have a code quality inspection that locates instances of a For
loop variable being explicitly tampered with inside the loop body.
Why
A For
loop that modifies its counter variable is poor practice and makes execution harder to follow and the code harder to debug when problems inevitably happen.
Example
This code should trigger the inspection:
Public Sub DoSomething()
Dim i As Long
For i = 1 To 3
Debug.Print i
i = i + 1
Next
End Sub
Output is 1
on first iteration, 3
on the second; i
is 5
after the loop.
QuickFixes
-
Specify a 'Step' increment
When the in-body increment is unconditional, this fix should be applicable: we take the sum of manual unconditional increment(s), add +1, and that's theStep
increment.Example code, after quickfix is applied:
Public Sub DoSomething() Dim i As Long For i = 1 To 3 Step 2 Debug.Print i Next End Sub
Output is
1
on first iteration, then3
on the second;i
is still5
after the loop.
If the tampering is conditional (even only in part), we can't really offer a quickfix (or can we?), but we can still warn and recommend restructuring that loop.
Resources
- InspectionNames: 'For' loop counter is being tampered with.
- InspectionInfo: Avoid tampering with a 'For' loop variable inside the body of that loop: it makes the code harder to follow, and can easily introduce bugs in the logic. If the assignment is unconditional, consider specifying a 'Step' increment. If the assignment is conditional, consider restructuring the flow control to avoid needing to modify the loop variable.
- InspectionResults: 'For' loop variable '{0}' is explicitly assigned in the loop body.