MSBA-352 · Lesson 5 of 12 · 20 min
Codeunits and procedures
▶ Video coming soon A video version of this lesson is on the way.
By the end of October, the warranty app had tables Callum could fill in and pages he could find. It did nothing by itself. "Right now it is a nicer spreadsheet," Noor said at the next session. "The value is in what happens when a grinder ships." Before connecting anything to posting, Joss had to learn where logic lives in AL and how to write it so that someone else can read, test and reuse it. This lesson covers codeunits, procedures, variables and parameters, access modifiers, error handling, labels, transactions, and running code in the background.
Where logic lives
AL code can sit in many places: table triggers, field validation triggers, page triggers, action triggers and report triggers. All of them are legitimate, but Noor's rule was that business logic belongs in codeunits. A page action should be one line that calls a procedure. A table trigger should enforce rules about that table's own data and little else. The reasons are practical. Logic in a codeunit can be called from a page, a report, an API, a job queue entry and a test, all in the same way. Logic buried in a page action runs only when a person clicks that button.
A codeunit is an object that contains procedures and, optionally, an OnRun trigger that runs when the codeunit itself is run. Joss's main codeunit, CNF Warranty Mgt., holds the procedures the rest of the app calls: register a serial number, calculate an end date, void a registration, check whether a claim is in warranty.
A first procedure
namespace Quarrystone.CorbelFinch.Warranty;
using Microsoft.Inventory.Item;
codeunit 50100 "CNF Warranty Mgt."
{
procedure CalcEndDate(ItemNo: Code[20]; StartDate: Date): Date
var
Item: Record Item;
begin
Item.SetLoadFields("CNF Warranty Period");
Item.Get(ItemNo);
if Format(Item."CNF Warranty Period") = '' then
Error(NoPeriodErr, ItemNo);
exit(CalcDate('<-1D>', CalcDate(Item."CNF Warranty Period", StartDate)));
end;
procedure IsInWarranty(Registration: Record "CNF Warranty Registration"; OnDate: Date): Boolean
begin
if Registration.Status <> Registration.Status::Active then
exit(false);
exit((OnDate >= Registration."Start Date") and (OnDate <= Registration."End Date"));
end;
var
NoPeriodErr: Label 'Item %1 has no warranty period. Set Warranty Period on the item card.', Comment = '%1 = item number';
}A procedure has a name, parameters with types, an optional return type, local variables in a var block, and a body between begin and end. exit returns a value and leaves the procedure. AL statements end with semicolons, assignments use :=, and comparisons use = and <>. Text literals sit in single quotes. None of this was hard for Joss after Python; the surprises were elsewhere.
The end date calculation was the first real business rule, and it started an argument. Callum's rule, from the manufacturers' warranty cards, is that a 24-month warranty on a grinder shipped on March 10 covers it up to and including March 9 two years later. CalcDate with the item's DateFormula of 24M gives March 10; subtracting one day gives March 9. Joss first wrote it without the minus one day and the test with Callum caught it. Noor mentioned that Quarrystone's sister team on the finance and operations side had shipped exactly the same off-by-one bug in a pump warranty module that autumn. "Date rules are where business people and developers misunderstand each other," she said. "Write the rule in words in the procedure's documentation and get the customer to agree to the words."
Variables, parameters and return values
Variables declared in a procedure's var block are local: they exist only while the procedure runs. Variables declared in the codeunit's own var block are global to that codeunit. Noor kept globals for labels and for nothing else, because globals make it hard to know which procedure changed what.
Parameters are passed by value unless they are marked var, in which case they are passed by reference and changes made inside the procedure are seen by the caller. Record parameters follow the same rule, with one twist that catches every new AL developer: a record passed by value is a copy of the variable, including its filters, but the database row it points to is the same. Modifying the copy and calling Modify writes to the database. Passing var Registration makes the intent explicit.
| Declaration | Meaning | When to use |
|---|---|---|
| Registration: Record "CNF Warranty Registration" | A copy of the caller's variable | The procedure only reads the record |
| var Registration: Record "CNF Warranty Registration" | The caller's own variable | The procedure changes the record or its filters and the caller needs the result |
| Registration: Record "CNF Warranty Registration" temporary | A temporary record | Working in memory without touching the database |
| ItemNo: Code[20] | A simple value | Most input parameters |
Procedures can return a value with a type after the parameter list, as CalcEndDate returns a Date. A procedure that only does something has no return type. When a procedure needs to return several values, it uses var parameters, or returns a record or a small temporary table.
Access modifiers
By default a procedure is public: any object in this app, and any other app that depends on this one, can call it. Three modifiers narrow that.
| Modifier | Who can call it |
|---|---|
| (none) or public | Any code in this app and in apps that depend on it |
| internal | Only code in this app (and apps it explicitly grants access to) |
| local | Only code in the same object |
| protected | Code in the same object and in extensions of it, used on tables and pages |
An object can also be marked Access = Internal, which hides the whole object from other apps. Noor's advice was to make everything local or internal until there is a reason to expose it. A public procedure is a promise: another app may come to depend on it, and changing its parameters later breaks that app. For a per-tenant extension with no dependants the risk is small, but the habit protects Quarrystone when a component moves into a shared app.
Registering a serial number
The heart of the app is the procedure that creates a registration. Joss wrote it to take everything it needs as parameters, so it does not care whether it is called from posting, from a migration of old spreadsheet rows, or from a test.
procedure RegisterSerialNo(SerialNo: Code[50]; ItemNo: Code[20]; CustomerNo: Code[20]; ShipmentNo: Code[20]; ShipDate: Date)
var
Registration: Record "CNF Warranty Registration";
begin
if not ShouldRegister(ItemNo) then
exit;
if AlreadyRegistered(SerialNo, ItemNo) then
exit;
Registration.Init();
Registration."Serial No." := SerialNo;
Registration."Item No." := ItemNo;
Registration."Customer No." := CustomerNo;
Registration."Shipment No." := ShipmentNo;
Registration."Start Date" := ShipDate;
Registration."End Date" := CalcEndDate(ItemNo, ShipDate);
Registration.Status := Registration.Status::Active;
Registration.Insert(true);
end;
local procedure ShouldRegister(ItemNo: Code[20]): Boolean
var
Item: Record Item;
begin
Item.SetLoadFields("CNF Register Warranty");
if not Item.Get(ItemNo) then
exit(false);
exit(Item."CNF Register Warranty");
end;
local procedure AlreadyRegistered(SerialNo: Code[50]; ItemNo: Code[20]): Boolean
var
Registration: Record "CNF Warranty Registration";
begin
Registration.SetRange("Serial No.", SerialNo);
Registration.SetRange("Item No.", ItemNo);
Registration.SetRange(Status, Registration.Status::Active);
exit(not Registration.IsEmpty());
end;Each helper does one thing and has a name that says what. The public procedure reads almost like Callum's requirement: if the item should be registered and has not been, create a registration starting on the ship date. Insert(true) runs the table's OnInsert trigger, which checks the required fields from lesson 3.
The duplicate check is a business decision as much as a technical one. A machine can come back on a return and be sold again to another café. Callum decided that the original registration is voided when the return is posted, and a new sale creates a new registration only if no active one exists. That is why AlreadyRegistered looks only at active registrations, and why the unique key from lesson 3 later gained the shipment number: the same serial number can now appear more than once, once per sale.
Errors, confirmations and labels
AL has a few built-in ways to talk to the user. Error stops the code, rolls back everything written to the database in the current transaction and shows a message. Message shows information and lets the code continue. Confirm asks a yes or no question and returns a Boolean. StrMenu offers a few choices.
Every text shown to users should be a Label, declared in a var block with a name, the text, and a Comment that tells translators what the placeholders mean. Labels are collected into a translation file when the TranslationFile feature is on in app.json, so the app can be translated later without changing code. Placeholders, written as a percent sign followed by a number, are filled in by Error, Message and StrSubstNo. CodeCop warns when a message uses a hard-coded string instead of a label.
procedure VoidRegistration(var Registration: Record "CNF Warranty Registration")
begin
if Registration.Status = Registration.Status::Void then
Error(AlreadyVoidErr, Registration."Serial No.");
if not Confirm(VoidQst, false, Registration."Serial No.", Registration."Customer Name") then
exit;
Registration.Status := Registration.Status::Void;
Registration.Modify(true);
end;
var
AlreadyVoidErr: Label 'The warranty for serial number %1 is already void.', Comment = '%1 = serial number';
VoidQst: Label 'Void the warranty for serial number %1 sold to %2?', Comment = '%1 = serial number, %2 = customer name';Noor added one caution. Confirm and Message need a user at a screen. When code runs from an API call, a job queue entry or a background session, there is nobody to click OK. A Confirm in a background session fails. Procedures that might run without a user should not ask questions; the page action asks, then calls a procedure that does the work silently. Joss later split VoidRegistration into a page-level confirmation and a procedure that only voids.
Transactions and error handling
Business Central wraps each user action in a transaction. Everything written to the database is committed when the action finishes successfully, and everything is rolled back if an error occurs. That is why an Error in the middle of posting leaves no half-posted documents. Calling Commit ends the transaction early, which is almost never right in extension code and is forbidden in event subscribers that run inside posting (lesson 6).
Sometimes code needs to try something and continue if it fails. Two patterns exist. Running a codeunit with if Codeunit.Run(...) then catches any error inside it, rolls back that codeunit's writes and returns false; the error text is available from GetLastErrorText. A procedure marked with the [TryFunction] attribute returns false instead of raising an error, but database writes inside it are not rolled back separately, so it is meant for checks and external calls, not for writing data. Joss used neither in version 1, on Noor's advice that most errors in warranty registration should stop the posting and be fixed, not silently skipped.
Codeunit properties and subtypes
| Property | Effect |
|---|---|
| Subtype = Normal | An ordinary codeunit (the default) |
| Subtype = Install or Upgrade | Runs during installation or upgrade of the app (lesson 2) |
| Subtype = Test, TestRunner | Contains automated tests or runs them (next course) |
| TableNo | Lets the codeunit be run with a record, which OnRun receives as Rec |
| SingleInstance = true | Keeps one instance for the whole session, so globals survive between calls |
| Permissions | Grants the codeunit indirect permissions to tables (lesson 10) |
| Access = Internal | Hides the codeunit from other apps |
Background work: job queues and scheduled tasks
Registrations become Expired when their end date passes. That should happen every night, without anyone clicking a button. Business Central has two mechanisms. The job queue runs codeunits and reports on a schedule set up by an administrator on the Job Queue Entries page, with logging and retries; it is what Corbel & Finch already uses for the nightly Adjust Cost job from the inventory course. The TaskScheduler data type lets code schedule a one-off background task itself.
Joss wrote a small codeunit, CNF Expire Warranties, whose OnRun calls ExpireOverdue from lesson 3. Callum then created a job queue entry in UPDATE-TEST with Object Type to Run set to Codeunit, the codeunit's ID, and a recurrence of every night at 1:00. No scheduling logic lives in the app itself, which means Callum can change the time without a developer.
codeunit 50102 "CNF Expire Warranties"
{
trigger OnRun()
var
WarrantyMgt: Codeunit "CNF Warranty Mgt.";
begin
WarrantyMgt.ExpireOverdue();
end;
}Worked problem
Moving logic out of a page
An earlier draft had the end date calculation inside the OnValidate trigger of the Start Date field on the registration card page. Callum now wants old spreadsheet warranties imported with the same rule. What should Joss change?
Show solution
- Move the calculation into CalcEndDate in the CNF Warranty Mgt. codeunit, with the item number and start date as parameters.
- Make the page trigger a single call to CalcEndDate.
- Write the import so it calls RegisterSerialNo, which already calls CalcEndDate.
- Now the rule exists in one place, and a fix to it fixes the card, the import and posting together.
Answer: Put business rules in codeunit procedures and call them from pages, imports and posting alike.
Reading code like a reviewer
Every procedure Joss wrote went through Noor's review, and her comments followed a pattern that Joss turned into a checklist. Does the procedure's name say what it does, as a verb? Does it do one thing? Are its parameters the minimum it needs, with var only where the caller needs changes back? Is it as private as it can be? Does every message use a label with a comment? Can it run without a user? Does it read only the fields it needs, with SetLoadFields? Would a test be easy to write for it? The last question was the most useful. If a test needs a posted sales order to check one date calculation, the calculation is in the wrong place; if it can be tested with three parameters, it is in the right one.
Common mistakes
MistakeWriting business logic inside page action triggers.
InsteadCall a codeunit procedure from the action.
MistakeMaking every procedure public by default.
InsteadStart local or internal and expose only what callers need.
MistakeUsing Confirm in code that may run from an API or the job queue.
InsteadAsk on the page, then call a procedure that does not interact with the user.
MistakeHard-coding message text in Error calls.
InsteadUse labels with comments explaining each placeholder.
MistakeCalling Commit to save partial work.
InsteadLet the transaction commit at the end of the action; use Codeunit.Run when isolation is needed.
Summary and key terms
- Business logic belongs in codeunits so pages, reports, APIs, job queues and tests can all reuse it.
- Procedures have parameters, local variables, an optional return value and an access level.
- var parameters pass by reference; record parameters by value still point to the same database row.
- Error rolls back the transaction; Message and Confirm need a user; labels make text translatable.
- Codeunit.Run and TryFunction handle expected failures; Commit is almost never right in extension code.
- The job queue runs codeunits on a schedule that administrators control.
- Codeunit
- An AL object that holds procedures and an optional OnRun trigger.
- Procedure
- A named block of code with parameters and an optional return value.
- Label
- A translatable text constant with a comment for translators.
- Transaction
- The unit of database work that commits together or rolls back together.
- TryFunction
- An attribute that makes a procedure return false instead of raising an error.
- Job queue
- The scheduler that runs codeunits and reports in the background.
- Access modifier
- A keyword such as local or internal that limits who can call a procedure.
Practice problems
Work each problem on paper first, then reveal the answer to check.
A grinder with a 24M warranty ships on March 10, 2027. What end date does CalcEndDate return?
Show answer
March 9, 2029: CalcDate with 24M gives March 10, 2029, and one day is subtracted.
Why is AlreadyRegistered a local procedure?
Show answer
It is a helper for RegisterSerialNo; nothing outside the codeunit needs it, and keeping it local lets Joss change it freely.
Why should the nightly expiry not ask the user anything?
Show answer
It runs in the job queue, where there is no user to answer, so a Confirm would fail.
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.