ADVERTISEMENT
AL Objects and Extensibility

Codeunits in AL

Learn about codeunits in AL and how they are used to implement business logic in Business Central. Understand codeunit objects, procedures, events, and execution patterns in AL.

What you will accomplish

Use a codeunit when logic represents reusable behaviour or process orchestration rather than stored data or page layout. A codeunit becomes valuable when the same rule must run from more than one UI or background context.

Before you start

Know Record variables, procedures, and basic table validation. Use a sandbox extension with a reserved object ID range.

Expected learning result

You should be able to place a small process in a codeunit, call it from a page action, and test the result without duplicating the rule in the page.

Codeunits in AL
Codeunits in AL

Codeunits in AL are used to encapsulate business logic and system behavior in a structured, reusable, and upgrade-safe way. They are the primary objects responsible for processing, calculations, validations, and orchestration of business processes in Business Central.

This page explains what codeunits are, why they exist, and how they should be used correctly, with practical examples. The goal is to help learners understand where business logic belongs before diving into events, subscribers, or advanced patterns.


What Is a Codeunit in AL?

A codeunit is an AL object that contains procedures (methods) used to perform business logic. Unlike pages or reports, codeunits do not display data and do not define layouts. Unlike tables, they do not define storage. Their sole responsibility is behavior.

A codeunit:

• Executes logic
• Manipulates records
• Coordinates processes
• Exposes reusable procedures

A codeunit does not:

• Store data
• Define UI
• Replace tables or pages

Codeunits are the logic layer of Business Central.

Why Codeunits Exist in Business Central

ERP systems require complex, reusable logic:

• Posting routines
• Calculations
• Validations
• Automation
• Integration handling

Placing this logic in pages or reports leads to duplication and instability. Codeunits exist to:

• Centralize business logic
• Promote reuse
• Improve maintainability
• Support event-driven extensibility

They are essential for clean architecture.

Basic Structure of a Codeunit

A codeunit is defined using the codeunit object and consists primarily of procedures and optional triggers.

Example: Basic Structure

AL

codeunit 50160 "Customer Feedback Management"
{
}
    

The object itself does nothing until procedures or triggers are defined.

ADVERTISEMENT

Simple Codeunit Example

The following example shows a codeunit that encapsulates a business operation.

Example: Simple Codeunit

AL

codeunit 50160 "Customer Feedback Management"
{
    procedure CreateFeedback(CustomerNo: Code[20]; FeedbackText: Text[250])
    var
        Feedback: Record "Customer Feedback";
    begin
        Feedback.Init();
        Feedback."Customer No." := CustomerNo;
        Feedback."Feedback Text" := FeedbackText;
        Feedback.Insert(true);
    end;
}
    

This codeunit:

• Contains reusable logic
• Interacts with a table
• Does not depend on UI
• Can be called from pages, reports, or other codeunits

Calling a Codeunit From a Page

Codeunits are commonly invoked from UI actions.

Example: Calling Codeunit from Page

AL

var
    FeedbackMgt: Codeunit "Customer Feedback Management";
begin
    FeedbackMgt.CreateFeedback("Customer No.", 'Good service');
end;
    

This keeps the page clean and delegates logic to the correct layer.

Codeunit Triggers

Codeunits support triggers such as:

• OnRun

Example: Codeunit Trigger

AL

trigger OnRun()
begin
    // Entry point logic
end;
    

The OnRun trigger is typically used when:

• The codeunit is executed directly
• It acts like a processing job
• It replaces a report for pure logic execution

Single-Instance Codeunits

Some codeunits are marked as single-instance, meaning their state is preserved during a session.

SingleInstance = true;

These are commonly used for:

• Caching
• Session-level state
• Central coordination

They must be used carefully to avoid side effects.

ADVERTISEMENT

Access Modifiers and Reusability

Procedures in codeunits can be:

• Public (callable from other objects)
• Local (internal use only)

This supports encapsulation and controlled exposure of logic.

Where Codeunits Fit in the Architecture

Codeunits sit at the center of business processing:

• Pages call codeunits
• Reports call codeunits
• XML Ports call codeunits
• Event subscribers often live in codeunits

They should not depend on UI objects.

Common Beginner Mistakes With Codeunits

Developers often:

• Put UI logic in codeunits
• Write very large, monolithic codeunits
• Ignore procedure visibility
• Duplicate logic instead of reusing procedures

Avoiding these mistakes leads to cleaner solutions.

Summary

Codeunits in AL define how Business Central behaves. They are the core of business logic, responsible for processing data and enforcing business rules in a reusable and maintainable way.

A well-designed codeunit:

• Has a clear responsibility
• Exposes meaningful procedures
• Avoids UI dependencies
• Supports extensibility

Understanding codeunits is essential before learning Events, Subscribers, and Interfaces.

Practical check: Move customer review logic out of a page action

A page action should mark an eligible customer for review. Put the eligibility check and record update in a codeunit procedure; leave only user interaction in the page.

Steps and evidence to inspect

  1. Create a procedure that receives the customer record and validates the precondition.
  2. Apply the field update through Validate and persist it once.
  3. Call the procedure from a page extension and from a test codeunit or second controlled caller.

Expected result

Both callers produce the same result because the business rule has one implementation. The page contains no duplicated eligibility logic.

If the result is different

If changes disappear, check whether the record is passed by value or var and whether Modify is intentionally called. If the page shows stale data, refresh after the process rather than repeating the update in UI code.

Version and implementation boundary

Transaction scope and commits need deliberate design. Do not add COMMIT merely to make a demo appear successful; consider rollback, locking, and callers first.

Authoritative reference: Microsoft Learn — Codeunit object. The scenario and interpretation above are original to ScrutnLearn.

Stay Updated

Get the latest tutorials, tips and resources delivered to your inbox.