Build reliable AL foundations
Reliable AL code starts with values that have clear meanings and controlled lifetimes. Accurate declarations make invalid states harder to create and make procedure contracts easier to understand.
Select types that express intent
AL includes simple types, such as Boolean, Integer, Decimal, Date, Code, and Text, and complex types, such as Record, Codeunit, List, Dictionary, JsonObject, InStream, and ErrorInfo. Choose a type for the value's meaning instead of its current appearance.
For example, an imported date arrives as text, but it shouldn't remain text after parsing. A priority with a fixed set of supported values belongs in an enum rather than an unrestricted string. A Business Central item belongs in a Record Item variable rather than several unrelated text variables.
Length also forms part of the contract. Code[20] normalizes letters to uppercase and removes leading and trailing spaces. Text[20] preserves casing and spaces. Match field-backed variables to the table field where practical, and use CopyStr when an external value must be constrained deliberately.
var
Item: Record Item;
ItemNo: Code[20];
ReviewDate: Date;
ImportedCount: Integer;
HasHeader: Boolean;
This declaration communicates more than a collection of generic strings. It identifies a domain record, a normalized key, a parsed date, a counter, and a state flag.
Limit variable lifetime and mutation
Declare a variable in the narrowest scope that owns its state:
- Use a local variable when only one procedure needs the value.
- Use a parameter when a caller supplies or receives the value.
- Use a global variable only when several triggers or procedures in the same object share necessary state.
- Use a protected variable only when an extension object must access the variable through inheritance.
Parameters default to value semantics. Add var when a procedure intentionally changes the caller's variable. The keyword makes that side effect visible in the signature.
local procedure TryReadDate(DateText: Text; var ReviewDate: Date): Boolean
begin
exit(Evaluate(ReviewDate, DateText));
end;
Avoid using globals as hidden output parameters. A procedure that returns a value or changes an explicit var parameter is easier to test and reason about.
Build expressions with predictable conversions
AL supports arithmetic, comparison, logical, and string operators. Operator precedence determines evaluation order, so use parentheses when an expression combines conditions with different meanings.
if Item.Blocked or ((ReviewDate < WorkDate()) and (Priority = Priority::High)) then
Error(InvalidReviewErr);
Don't depend on an implicit conversion when input can be malformed. Use Evaluate to parse text into a typed value and inspect its Boolean result. Use Format to convert a typed value to text for display or serialization. This boundary keeps parsing decisions close to the external input.
For more information, see AL data types and Variables in AL.