Skip to content

Flag 'For' loop counter tampering in loop body #4930

@retailcoder

Description

@retailcoder

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

  1. 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 the Step 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, then 3 on the second; i is still 5 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    difficulty-02-duckyResolving these involves the internal API, but with relatively easy problems to solve.enhancementFeature requests, or enhancements to existing features. Ideas. Anything within the project's scope.feature-inspectionsup-for-grabsUse this label in conjunction with a difficulty level label, e.g. difficulty-02-ducky

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions