Decisions & loops
Express decisions directly and stop loops at a clearly defined boundary.
Use an early guard for invalid input#
An If condition should describe the decision, not the desired screen text. The Greeting example in procedures rejects an empty normalized name before the success path. That order prevents a success message from briefly appearing for invalid input.
Select one named case#
Public Function StateCaption(ByVal state As TaskState) As String
Select Case state
Case TaskState.Ready
StateCaption = "Ready"
Case TaskState.Running
StateCaption = "Working"
Case Else
StateCaption = "Complete"
End Select
End FunctionTaskState is an Enum declared in the same module. The caller uses names such as TaskState.Running instead of unexplained integer codes. Case Else gives the remaining path a deliberate result.
Keep the enum declaration with the example#
Public Enum TaskState
Ready = 0
Running = 1
Complete = 2
End EnumA public enum in a standard module can be shared. Name its members for states, not for labels that may change in the UI.
Make loop progress visible#
Public Function CountDown(ByVal start As Long) As Long
Dim value As Long
value = start
Do While value > 0
value = value - 1
Loop
CountDown = value
End FunctionCountDown(3) returns 0. The loop updates the same variable its condition tests. A start value of zero or a negative value skips the body and returns that start value; it is not silently clamped.
Choose the right loop for the data#
Use a counted For loop when positions matter, and read array bounds with LBound/UBound. Use For Each for values in a supported collection. JSON arrays and Recordsets have their own zero-based access APIs; a Collection’s positions are one-based. Do not transfer an indexing assumption between them.
Test the branch, not only the happy path#
For each decision, write down an input that takes each branch. For a loop, test zero iterations, one iteration and several. The debugging exercise intentionally reverses a condition to demonstrate why a successful Check does not prove your rule is correct.
20f4bfed6b · Build manifestSources & maintenance
Original web explanation, reviewed against these repository sources. API tables and example files follow the implementation.
docs/manual/21-language-reference.mddocs/manual/11-language-toolkit.mdsite/examples/LanguageWorkbench/Main.bas