Chapter 6: Control Structures
Objectives
By the end of this chapter you will be able to:
- Use
if,case, and loops appropriately in AL - Choose between
for,while, andrepeat..untilbased on intent - Apply safe error handling patterns for business rules
- Write control flow that scales to real data volumes
6.1 Conditional statements (if and case)
Use if for binary choices or short decision trees, and case when there are several discrete branches.
if Score >= 90 then
Grade := 'A'
else
if Score >= 80 then
Grade := 'B'
else
Grade := 'C';
case DocumentStatus of
DocumentStatus::Open:
HandleOpen();
DocumentStatus::Released:
HandleReleased();
else
Error('Unsupported status: %1', Format(DocumentStatus));
end;
6.2 Looping constructs
Choose the loop type that matches the business behavior:
for: known iteration count (for example, fixed installments)while: condition-driven iterationrepeat..until: record traversal afterFindSet
if Customer.FindSet() then
repeat
ProcessCustomer(Customer);
until Customer.Next() = 0;
Chapters 9 and 13 use this pattern heavily.
6.3 Error handling and assertions
Use Error to stop invalid transactions early.
if Amount <= 0 then
Error('Amount must be greater than zero.');
In tests (Chapter 14), prove behavior with assertions instead of checking it by hand in the UI.
6.4 Control-flow quality guidelines
- Keep nesting shallow by extracting helper procedures.
- Fail fast on invalid data.
- Never use a loop when a filtered set would do (see Chapter 13).
6.5 Control-structure decision map (visual guide)
flowchart TD
A[Need branching or iteration?] --> B{Single yes/no decision?}
B -->|Yes| C[Use if]
B -->|No| D{Multiple discrete states?}
D -->|Yes| E[Use case]
D -->|No| F{Known number of iterations?}
F -->|Yes| G[Use for]
F -->|No| H{Iterating record set after FindSet?}
H -->|Yes| I[Use repeat..until]
H -->|No| J[Use while]
Chapter summary
In this chapter you:
- Applied AL conditionals and loops, with clear criteria for choosing each one
- Used repeatable record-iteration patterns
- Added safe, explicit error handling to business rules
- Prepared control-flow techniques that codeunits and tests reuse
Tasks
- Branching choice. Replace one overgrown
ifchain with acasewhere appropriate. - Decision fallback. Add an
elsebranch (orcase else) that raises anErrorfor unsupported state values. - Loop correction. Refactor one loop to use
FindSet+repeat..untilfor record traversal. - Loop intent check. Convert one loop to
forwhen the iteration count is known ahead of time. - Guard clause. Add one fail-fast
Errorthat protects invalid input before any data changes. - Try it yourself. Extract one nested block into a helper procedure to reduce nesting depth.
Check your work: compare your answers with the Chapter 6 solutions, then verify your loop and branching style aligns with Chapters 9, 13, and 14 patterns.