Do loop has no While or Until condition

ID

vbnet.maintainability.loops_while_until_condition

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Control Flow

Language

VB.NET

Description

Reports a Do …​ Loop written with no While or Until condition on either the Do line or the Loop line. Such a loop has no termination test of its own: it repeats forever unless the body executes an Exit Do, a Return, a GoTo, or throws.

Rationale

The loop header is where a reader looks to find out when the loop ends. With no condition there, the termination rule is hidden somewhere in the body - or missing altogether, which hangs the thread and, in a service, holds a request, a connection or a lock indefinitely. Loops that depend on a buried Exit Do are also fragile under maintenance: adding an early Continue Do or an extra branch above the exit can silently make the loop non-terminating.

The following code illustrates the pattern detected by this rule:

Public Sub DrainRelyingOnExit()
    ' FLAGGED: Do loop has no While or Until condition
    Do
        If _pending.Count = 0 Then
            Exit Do
        End If
        Handle(_pending.Dequeue())
    Loop
End Sub

Remediation

State the termination condition in the loop header with Do While / Do Until when it must be tested before the first iteration, or on the Loop line with Loop While / Loop Until when the body must run at least once. If the loop really is meant to run until an event stops it, make that explicit with a named flag in the condition rather than an Exit Do in the middle.

' Before: termination depends on an Exit Do inside the body
Do
    If pending.Count = 0 Then
        Exit Do
    End If
    Handle(pending.Dequeue())
Loop

' After: the condition is visible in the header
Do While pending.Count > 0
    Handle(pending.Dequeue())
Loop

Configuration

This detector does not need any configuration.