MSBA-359 · Lesson 8 of 12 · 22 min
Code-reading questions
▶ Video coming soon A video version of this lesson is on the way.
Joss could write AL faster than he could read it. That is common among developers who learned with a compiler at their side: the editor underlines mistakes, IntelliSense fills in parameters, and running the code answers any doubt. The exam takes all of that away. "In the exam room the code is a picture," Noor said, "and you are the compiler." She spent two sessions in mid-November giving him short listings on paper and asking what they would do. This lesson collects those listings, all original, with the reasoning that leads to each answer.
Code-reading items appear across the outline, but most often in the AL objects and logic areas, which together are worth about half the exam. They come in a few shapes: predict the result of a snippet, find the line that causes a problem, complete a gap in a drop-down, or choose which version of a snippet meets a requirement.
A method for reading code under time pressure
Read the question first. "What is the value of X after the code runs?" and "Which line causes the error?" need different reading. Identify the context: what kind of object, which trigger, which variables are records and whether any are temporary. Trace the data line by line, writing down values that change, filters that apply and whether each record call runs triggers. Check the usual traps: Validate versus assignment, Insert and Modify with or without true, FlowFields without CalcFields, var versus value parameters, temporary records, zero-based versus one-based indexes, and integer versus decimal arithmetic. Answer and mark the item if any step relied on a guess.
The traps are worth memorizing because they are where exam writers put the wrong answers. Each listing below exercises at least one of them.
Listing 1: triggers and validation
procedure CloseOldClaims()
var
Claim: Record "CNF Warranty Claim";
begin
Claim.SetRange(Status, Claim.Status::Open);
Claim.SetFilter("Claim Date", '<%1', CalcDate('<-90D>', WorkDate()));
if Claim.FindSet(true) then
repeat
Claim.Status := Claim.Status::Closed;
Claim.Modify();
until Claim.Next() = 0;
end;Question: the claim table's OnModify trigger sets a "Last Modified By" field, and the Status field's OnValidate trigger sends an email to the customer. After the procedure runs, are the emails sent and is "Last Modified By" updated?
Neither. Claim.Status := ... is a direct assignment, so the Status field's OnValidate trigger does not run; only Validate runs it. And Modify() without true does not run the table's OnModify trigger. If the requirement is to notify customers and record who changed the claims, the loop needs Claim.Validate(Status, Claim.Status::Closed) and Claim.Modify(true). Exam options in this style often include "both", "only the email" and "only the field"; trace each call separately.
Notice also what the code does right. It filters before finding, uses FindSet(true) because it will modify records in the loop, and calculates the date relative to the work date rather than today, which lets a user run it as if on another date.
Listing 2: date formulas
StartDate := DMY2Date(18, 11, 2026);
FirstOfNextMonth := CalcDate('<CM+1D>', StartDate);
WarrantyEnd := CalcDate('<24M-1D>', DMY2Date(15, 1, 2027));
QuarterStart := CalcDate('<-CQ>', StartDate);Question: what are the three calculated dates?
CM means the end of the current month, so <CM+1D> from November 18, 2026 is November 30 plus one day: December 1, 2026. <24M-1D> from January 15, 2027 adds 24 months to reach January 15, 2029, then subtracts a day: January 14, 2029, the "day before the anniversary" rule the warranty extension uses. -CQ means the start of the current quarter: October 1, 2026. Date formula questions often hide the difference between C (current period boundary) and a plain unit, and between <1M> from January 31 (which gives the last day of February) and <CM>. Write the intermediate date down; it takes five seconds and saves a mark.
Listing 3: Code, Text and lengths
var
ShortCode: Code[10];
Name: Text[30];
begin
ShortCode := ' grinder-x ';
Name := 'Breakwater Blend';
Message('%1|%2|%3', ShortCode, StrLen(Name), CopyStr(Name, 1, 5));
end;Question: what does the message show?
A Code value is converted to uppercase and leading and trailing spaces are removed, so ShortCode holds GRINDER-X (nine characters, which fits). StrLen of "Breakwater Blend" is 16. CopyStr(Name, 1, 5) returns the first five characters, "Break"; AL strings are indexed from 1. So the message reads GRINDER-X|16|Break. Had the literal been longer than ten characters after trimming, the assignment would raise a runtime error about the string length: AL does not truncate silently on assignment. Use CopyStr with MaxStrLen when truncation is intended.
Listing 4: integer and decimal arithmetic
var
Bags: Integer;
PerCase: Integer;
Cases: Decimal;
Whole: Integer;
Left: Integer;
begin
Bags := 30;
PerCase := 12;
Cases := Bags / PerCase;
Whole := Bags div PerCase;
Left := Bags mod PerCase;
Cases := Round(Cases, 1, '>');
end;Question: what are Whole, Left and Cases at the end?
The / operator always produces a Decimal, so Bags / PerCase is 2.5. div is integer division, giving 2, and mod is the remainder, 6. Round(2.5, 1, '>') rounds up to 3. The direction argument of Round is '=' (nearest, the default, with halves rounded away from zero), '>' (up) or '<' (down); the precision argument is the unit to round to, such as 0.01 for cents. Questions about quantities per case or slab, like the Marrowick case in lesson 2, often turn on these operators.
Listing 5: FlowFields and partial records
Customer.SetLoadFields(Name, "Credit Limit (LCY)");
Customer.Get('C00010');
if Customer."Balance (LCY)" > Customer."Credit Limit (LCY)" then
Message(OverLimitMsg, Customer.Name);Question: Balance (LCY) is a FlowField. The customer owes far more than the limit. Does the message appear?
No. A FlowField has no stored value; it is calculated only by CalcFields (or SetAutoCalcFields before the read). Without that, Customer."Balance (LCY)" is zero, so the comparison is false. The SetLoadFields line is a second, quieter issue: it asks for partial loading of two fields, and if code later reads a normal field that was not loaded, the platform loads it with an extra database call. That is not an error, only a performance cost. The correct code calls Customer.SetAutoCalcFields("Balance (LCY)") before Get, or CalcFields after it.
Listing 6: events and the IsHandled pattern
// In app A
procedure PriceClaim(var Claim: Record "CNF Warranty Claim")
var
IsHandled: Boolean;
begin
OnBeforePriceClaim(Claim, IsHandled);
if IsHandled then
exit;
Claim."Repair Cost" := 40;
OnAfterPriceClaim(Claim);
end;
// In app B
[EventSubscriber(ObjectType::Codeunit, Codeunit::"CNF Claim Pricing", 'OnBeforePriceClaim', '', false, false)]
local procedure FreeForStaff(var Claim: Record "CNF Warranty Claim"; var IsHandled: Boolean)
begin
if Claim."Customer No." = 'STAFF' then
Claim."Repair Cost" := 0;
end;
[EventSubscriber(ObjectType::Codeunit, Codeunit::"CNF Claim Pricing", 'OnAfterPriceClaim', '', false, false)]
local procedure Surcharge(var Claim: Record "CNF Warranty Claim")
begin
Claim."Repair Cost" += 5;
end;Question: for a claim from customer STAFF, what is the repair cost after PriceClaim?
Trace it. The OnBefore subscriber sets the cost to 0 but never sets IsHandled, so the publisher continues and assigns 40. The OnAfter subscriber adds 5. The result is 45. If the developer of app B intended staff repairs to be free, the subscriber needed IsHandled := true, and then the OnAfter event would not be raised either, because the procedure exits before it. Exam items like this test whether you read every line of the publisher, not just the subscriber.
Listing 7: JSON indexes
Body := '{"lines":[{"item":"FC-BRK","qty":12},{"item":"FC-FOG","qty":3}]}';
Root.ReadFrom(Body);
Root.SelectToken('$.lines[1].qty', Token);
Qty := Token.AsValue().AsInteger();
Root.Get('lines', Token);
Count := Token.AsArray().Count();Question: what are Qty and Count?
JSON arrays are indexed from zero, so lines[1] is the second line and Qty is 3. The array has two elements, so Count is 2. This contrasts with AL text functions such as CopyStr and with List variables, which are indexed from 1. A question that mixes a JSON array with a List of [Text] is testing exactly that.
Listing 8: try methods and errors
[TryFunction]
local procedure TryParseQty(Value: Text; var Qty: Decimal)
begin
Evaluate(Qty, Value);
end;
procedure ImportLine(Value: Text)
var
Qty: Decimal;
begin
if not TryParseQty(Value, Qty) then
Error(BadQtyErr, Value, GetLastErrorText());
InsertLine(Qty);
end;Question: what happens when Value is "twelve"?
Evaluate fails inside the try method, which returns false instead of stopping. ImportLine then raises its own error with the value and the original message from GetLastErrorText, so the transaction stops and no line is inserted. This is the right use of a try method: catching a failure that has no database writes inside it. If TryParseQty had also inserted a record before failing, that insert would not be rolled back by the try method itself; only the later Error in ImportLine rolls back the whole transaction. Questions about try methods usually test that distinction.
Listing 9: completing an attribute
Drop-down items often show a line with gaps. Here is an original example in that style, written as text.
[EventSubscriber(ObjectType::[ A ], [ B ]::"Sales-Post", '[ C ]', '', false, false)]
local procedure RegisterWarranties(var SalesHeader: Record "Sales Header"; SalesShptHdrNo: Code[20])Question: Sales-Post is a codeunit, and the subscriber must run after a sales document is posted. Choose A, B and C.
A is Codeunit (the object type), B is Codeunit (the object reference prefix, as in Codeunit::"Sales-Post"), and C is the event name, OnAfterPostSalesDoc. Distractors would include Table and Page for A and B, and OnBeforePostSalesDoc or OnAfterPostSalesLine for C. The parameter list gives a clue: the subscriber takes the shipment header number, which exists only after posting. The two false arguments are SkipOnMissingLicense and SkipOnMissingPermission.
Listing 10: temporary records
procedure CountDraftLines(): Integer
var
TempLine: Record "Sales Line" temporary;
Line: Record "Sales Line";
begin
Line.SetRange("Document Type", Line."Document Type"::Order);
if Line.FindSet() then
repeat
TempLine := Line;
TempLine.Insert();
until Line.Next() = 0;
TempLine.DeleteAll();
exit(Line.Count());
end;Question: does this procedure delete sales order lines from the database, and what does it return?
It deletes nothing from the database. TempLine is a temporary record, so Insert and DeleteAll act only on the in-memory copy. The procedure returns the number of sales order lines in the database, unchanged. Questions about temporary records often show DeleteAll on a temporary variable and offer "all sales lines are deleted" as a frightening distractor. Read the variable declarations first; the word "temporary" is easy to miss.
Practicing code reading
Noor's advice for the remaining weeks was to read more code than he wrote. Microsoft's base application source is available through symbols and on GitHub, and reading one posting codeunit end to end, or the events in Sales-Post, trains the eye for real patterns. Joss set himself a target of one listing a day: write ten to twenty lines that exercise a trap, put them away overnight, and predict the result the next morning before running them in the container. By the end of November he had 23 listings, and his prediction rate had gone from about six in ten to nine in ten.
Listing 11: value and var parameters
procedure Caller()
var
Item: Record Item;
begin
Item.Get('FC-BRK');
SetBlocked(Item);
Message('%1', Item.Blocked);
end;
local procedure SetBlocked(Item: Record Item)
begin
Item.Blocked := true;
Item.Modify();
end;Question: after Caller runs, is item FC-BRK blocked in the database, and what does the message show?
The item is blocked in the database, because SetBlocked calls Modify on its own copy of the record, and Modify writes to the table. But the message shows No (false), because the parameter is passed by value: SetBlocked changed its copy, not the Caller's variable, which still holds the values read before the call. Had the parameter been declared var Item: Record Item, both would show the change. This distinction between the database and the variable in memory is one of the most common sources of confusion in AL code questions, and it also explains real bugs where a page shows stale values until it is refreshed.
Listing 12: Get and filters
Line.SetRange("Document Type", Line."Document Type"::Order);
Line.SetRange("Document No.", 'SO-1001');
if Line.Get(Line."Document Type"::Invoice, 'INV-77', 10000) then
Message('Found %1', Line."No.")
else
Message('Not found');Question: an invoice line INV-77 with line number 10000 exists. What is shown?
Get reads by primary key and ignores the filters set on the variable, so the invoice line is found and its number shown, even though the filters say Order and SO-1001. FindFirst, by contrast, respects filters. Exam options often include "Not found because the filters exclude it". Remember too that Get raises an error if the record does not exist and its return value is not used; written with if, as here, it returns false instead.
Writing your own listings
The best way to get faster at reading code is to write code designed to trick you. Joss's rule was that each listing should be no longer than fifteen lines, contain exactly one trap from the list at the start of this lesson, and have an answer he could check by running it in the container the next day. Writing the listing forces you to know the rule precisely; predicting it a day later tests whether the rule has stuck. After a month he could spot direct assignments, missing true flags and temporary declarations almost without reading, which left more time on the exam for the hard questions.
Listing 13: report triggers
dataitem(Registration; "CNF Warranty Registration")
{
column(No; "No.") { }
column(EndDate; "End Date") { }
trigger OnPreDataItem()
begin
SetRange(Status, Status::Active);
end;
trigger OnAfterGetRecord()
begin
if "End Date" > CalcDate('<60D>', WorkDate()) then
CurrReport.Skip();
Counted += 1;
end;
trigger OnPostDataItem()
begin
if Counted = 0 then
CurrReport.Quit();
end;
}Question: the table holds 40 active registrations, 6 of which end within 60 days of the work date, and 10 expired ones. How many rows reach the layout, and what is Counted?
OnPreDataItem filters the data item to active registrations, so the expired ones are never read. OnAfterGetRecord runs 40 times. For the 34 registrations ending later than 60 days out, CurrReport.Skip skips the rest of the trigger and leaves the record out of the dataset, so Counted is not incremented for them. Six rows reach the layout and Counted is 6. Had none qualified, CurrReport.Quit would stop the report without output. The trap is to forget that Skip ends the trigger immediately, so code after it does not run for skipped records; a candidate who counts 40 has missed that.
Listing 14: enums and interfaces
enum 50101 "CNF Claim Resolution Type" implements "CNF Claim Resolution"
{
Extensible = true;
DefaultImplementation = "CNF Claim Resolution" = "CNF Resolve Repair";
UnknownValueImplementation = "CNF Claim Resolution" = "CNF Resolve Unknown";
value(0; Repair) { }
value(1; Replace) { Implementation = "CNF Claim Resolution" = "CNF Resolve Replace"; }
value(2; Refund) { Implementation = "CNF Claim Resolution" = "CNF Resolve Refund"; }
}Question: which codeunit handles Repair, and which handles a value called Loaner that was added by another app which has since been uninstalled, leaving claims that still store its value?
Repair declares no implementation of its own, so DefaultImplementation applies: CNF Resolve Repair. A stored value whose enum extension no longer exists is unknown to the enum, so UnknownValueImplementation applies: CNF Resolve Unknown. Replace and Refund use their own declared implementations. The calling code never changes; it assigns the enum value to an interface variable and calls the interface's procedures. Questions on this listing usually offer "a runtime error" as the answer for the uninstalled value, which is what would happen without an UnknownValueImplementation.
Worked problem
Reading for the requirement
A question shows two versions of a loop that sets a "Reminder Sent" field on overdue registrations. Version A uses Registration.ModifyAll("Reminder Sent", true). Version B loops with FindSet(true), sets the field with Validate and calls Modify(true). The field's OnValidate trigger writes a log entry. The requirement says every change must be logged. Which version meets it?
Show solution
- Identify the requirement: the OnValidate trigger must run for each record.
- ModifyAll without true does not run any triggers; even ModifyAll with true runs OnModify, not the field's OnValidate.
- Version B validates each record, so OnValidate runs and the log entry is written.
Answer: Version B. Set-based methods are faster, but they skip field validation; choose them only when no per-record logic is required.
Common mistakes
MistakeAssuming direct assignment runs OnValidate.
InsteadOnly Validate runs the field's OnValidate trigger.
MistakeReading a FlowField without CalcFields.
InsteadCall CalcFields or SetAutoCalcFields first; otherwise the value is zero.
MistakeCounting JSON arrays from one.
InsteadJSON arrays start at zero; AL text positions and Lists start at one.
MistakeMissing the word temporary in a declaration.
InsteadRead declarations first; temporary records never touch the database.
MistakeReading only the subscriber in an event question.
InsteadTrace the publisher too; IsHandled and OnAfter events change the result.
Summary and key terms
- Read the question first, then the context, then trace the data and check the traps.
- Validate runs OnValidate; Insert, Modify and Delete run table triggers only with true.
- The / operator returns a Decimal; div and mod are integer operations; Round takes a precision and a direction.
- Code values are uppercased and trimmed; assigning too long a string raises an error.
- FlowFields need CalcFields; SetLoadFields is a performance hint, not a restriction.
- JSON arrays are zero-based; try methods catch errors but do not roll back writes.
- Direct assignment
- Setting a field with := without running its OnValidate trigger.
- Date formula
- An expression such as <CM+1D> that CalcDate applies to a date.
- div and mod
- Integer division and remainder operators in AL.
- Partial record
- A record read with SetLoadFields so only some fields are loaded.
- Temporary record
- A record variable that holds data in memory only.
- GetLastErrorText
- A function that returns the message of the last error caught.
Practice problems
Work each problem on paper first, then reveal the answer to check.
What is CalcDate('<CM>', 2026-11-18)?
Show answer
November 30, 2026.
What is 30 mod 12?
Show answer
6.
What does CopyStr('Foghorn', 1, 3) return?
Show answer
Fog.
Does DeleteAll on a temporary record variable delete database rows?
Show answer
No.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.