Creating and Accessing Codeunits
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 11 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Module: Develop Using AL Objects
Section: Design XMLports and Codeunits
Lesson Title: Creating and Accessing Codeunits
Introduction: Why Codeunits Matter in AL
In the world of Business Central development, the Codeunit is the fundamental building block for logic. While tables store your data and pages provide the interface for users, Codeunits are where the "heavy lifting" happens. Think of a Codeunit as a container for your AL (Application Language) code that does not belong to a specific UI element or database record. If you have a business process, a calculation, or an integration task that needs to be performed, you will almost certainly be putting that logic inside a Codeunit.
Understanding how to design, create, and access Codeunits is the single most important skill for a developer working with AL. Without Codeunits, your logic would be scattered across various triggers on pages and tables, leading to "spaghetti code" that is difficult to maintain, test, and upgrade. By centralizing your logic, you create an environment where code is reusable, easier to debug, and significantly cleaner. This lesson will guide you through the lifecycle of a Codeunit—from its initial creation to advanced access patterns—and teach you how to write code that professional developers rely on daily.
Not read yet
What is a Codeunit?
At its core, a Codeunit is an object type in AL that contains no data-bound interface. Unlike a Page, which is tied to a table, or a Report, which is tied to a dataset, a Codeunit is purely a functional object. It is a class-like structure where you define global variables, functions, and procedures that can be called from anywhere else in your application.
When you create a Codeunit, you are essentially defining a service. You are telling the system: "Here is a collection of tools that I can use to manipulate data, communicate with external services, or perform complex calculations." Because Codeunits are highly modular, they are the primary vehicle for implementing business logic that needs to be triggered by different events, such as a user clicking a button on a page or a background job scheduled to run at midnight.
Callout: Codeunits vs. Other Objects It is helpful to think of the difference between object types in terms of responsibility. Tables are responsible for data structure and validation. Pages are responsible for user interaction and data presentation. Reports are responsible for data analysis and document generation. Codeunits, by contrast, are responsible for action. They are the "verbs" of your application, whereas tables are the "nouns."
Not read yet
Creating Your First Codeunit
Creating a Codeunit in Business Central is straightforward. Using the AL Language extension in Visual Studio Code, you simply create a new file with the .al extension and use the tcodeunit snippet. This generates the basic skeleton of the object.
Step-by-Step Creation
- Open your project folder in Visual Studio Code.
- Right-click in the Explorer view and select "New File."
- Name your file using the format
MyCodeunit.Codeunit.al. - Type
tcodeunitand press Tab. - Provide a unique ID and a descriptive name for your Codeunit.
The resulting code will look like this:
codeunit 50100 "My Calculation Service"
{
trigger OnRun()
begin
// Logic placed here runs when the codeunit is executed directly
end;
procedure CalculateTax(Amount: Decimal): Decimal
begin
exit(Amount * 0.15);
end;
}
The OnRun trigger is a special trigger that executes whenever the Codeunit is called without a specific function name. While you can put logic here, it is often better practice to define specific procedures (like CalculateTax) so that you can call them explicitly by name.
Not read yet
Accessing Codeunits: The Basics
Once you have defined a Codeunit, you need to know how to trigger its functionality. Accessing a Codeunit is done by declaring a variable of type Codeunit followed by the name you gave it. Once declared, you can access any of its public procedures using the dot notation.
Basic Implementation Example
Let’s say you have a Page where a user enters an amount, and you want to calculate the tax using the Codeunit we created above.
page 50101 "Tax Calculator Page"
{
PageType = Card;
SourceTable = "Customer";
layout
{
area(Content)
{
field(Amount; Amount)
{
ApplicationArea = All;
}
}
}
actions
{
area(Processing)
{
action(Calculate)
{
ApplicationArea = All;
trigger OnAction()
var
TaxService: Codeunit "My Calculation Service";
Result: Decimal;
begin
Result := TaxService.CalculateTax(Amount);
Message('The tax is %1', Result);
end;
}
}
}
var
Amount: Decimal;
}
In this example, we declared TaxService as a variable of type Codeunit "My Calculation Service". By calling TaxService.CalculateTax(Amount), we successfully delegated the business logic to our Codeunit. This keeps the Page code clean and focused solely on the user interface.
Not read yet
Best Practices for Codeunit Design
Writing Codeunits is easy, but writing good Codeunits requires discipline. If you write code without a plan, you will end up with "God Objects"—massive Codeunits that do everything and are impossible to maintain.
1. Single Responsibility Principle
Each Codeunit should have one clear purpose. If your Codeunit is named GeneralTools, it is likely doing too much. Instead, create specialized Codeunits such as TaxCalculator, InventoryIntegration, or DocumentPosting. This makes your code easier to find and test.
2. Use Public and Local Procedures
By default, procedures in AL are public, meaning they can be called from any other object. If a procedure is only used within the Codeunit itself, mark it as local. This hides the implementation details from other developers and keeps your interface clean.
codeunit 50101 "Helper Methods"
{
procedure PublicMethod()
begin
// This can be called from anywhere
InternalLogic();
end;
local procedure InternalLogic()
begin
// This is hidden and only available within this Codeunit
end;
}
3. Keep Logic Stateless
Ideally, your Codeunits should be stateless, meaning they don't rely on global variables that change state over time. If a procedure requires input, pass that input as a parameter. If it needs to return data, use a return value. This makes your code predictable and much easier to debug because you don't have to worry about what happened in the Codeunit five minutes ago.
Tip: Passing Records When passing records to a Codeunit procedure, always pass them by reference using the
varkeyword if you intend to modify them. If you only need to read the data, you can pass them withoutvar, which prevents accidental modification.
Not read yet
Advanced Access Patterns
As your application grows, you will encounter scenarios where you need more control over how Codeunits interact.
Using Interfaces
Interfaces are a powerful feature that allows you to define a contract for your Codeunits. If you have multiple ways to perform a task—for example, calculating shipping costs via FedEx or UPS—you can define an interface called IShippingCalculator. Then, you create two different Codeunits that implement this interface.
interface IShippingCalculator
{
procedure Calculate(Weight: Decimal): Decimal;
}
codeunit 50102 "FedExCalculator" implements IShippingCalculator
{
procedure Calculate(Weight: Decimal): Decimal
begin
exit(Weight * 2.0);
end;
}
This allows your main application logic to call IShippingCalculator.Calculate() without needing to know which specific shipping provider is being used. This is a hallmark of professional-grade AL development.
Event Subscribers
Codeunits are also the home of event subscribers. When you need to run logic when a standard Business Central event occurs (like a record being inserted), you create a Codeunit and add a procedure with the [EventSubscriber] attribute.
codeunit 50103 "EventHandler"
{
[EventSubscriber(ObjectType::Table, Database::Customer, 'OnAfterInsertEvent', '', false, false)]
local procedure HandleCustomerInsert(var Rec: Record Customer)
begin
// This runs automatically whenever a customer is inserted
end;
}
Not read yet
Common Pitfalls and How to Avoid Them
Even experienced developers can fall into traps when working with Codeunits. Here are the most common mistakes and how to avoid them.
1. Hardcoding Values
Never hardcode IDs, names, or configuration values inside a Codeunit. If you need a tax rate, store it in a setup table and fetch it in your Codeunit. Hardcoding makes your code brittle and difficult to update when business requirements change.
2. Neglecting Error Handling
When a Codeunit performs a complex task, it might fail. Use Error() or TestField() to handle invalid data gracefully. If you are performing a series of database operations, consider using a try-catch pattern or ensuring that your logic respects the transaction boundaries of the system.
3. Over-complicating the OnRun Trigger
Some developers try to cram all their logic into the OnRun trigger. This is a bad idea because it makes the Codeunit impossible to test in pieces. Always break your logic into small, named procedures that do one thing well.
Warning: Transactional Integrity Be very careful when running multiple database updates inside a Codeunit. If an error occurs halfway through, Business Central will automatically roll back the transaction. If you have already sent an email or called an external API, you cannot "roll back" those actions. Always perform external side effects only after your database operations have succeeded.
Not read yet
Comparison: Codeunit vs. Other Logic Containers
To help you decide when to use a Codeunit versus other methods, consult the following table:
| Feature | Codeunit | Table Trigger | Page Trigger |
|---|---|---|---|
| Primary Use | Reusable Logic | Data Validation | UI Interaction |
| Scope | Global | Record-level | UI-level |
| Reusability | High | Low | None |
| Accessibility | Anywhere | Only via Table | Only via Page |
Testing Your Codeunits
One of the biggest advantages of using Codeunits is that they are highly testable. In Business Central, you can create a "Test Codeunit" that automatically runs your business logic and asserts that the results are correct. This is the cornerstone of automated testing.
To create a test, you define a Codeunit with the Subtype = Test. Inside, you write procedures that perform an action and then check the result.
codeunit 50104 "TestTaxCalculation"
{
Subtype = Test;
[Test]
procedure TestTax()
var
TaxService: Codeunit "My Calculation Service";
Result: Decimal;
begin
// Setup
// Exercise
Result := TaxService.CalculateTax(100);
// Verify
Assert.AreEqual(15, Result, 'Tax calculation is incorrect');
end;
var
Assert: Codeunit "Assert";
}
By writing these tests as you develop, you ensure that your code remains stable even as you add new features. This is a "best practice" that separates hobbyist developers from professional AL engineers.
Not read yet
Practical Example: A Comprehensive Integration
Let’s imagine we need to build a system to log every time a sales order is deleted. We want to centralize this logic so we can easily change the logging format later.
- Create the Logger Codeunit:
codeunit 50105 "AuditLogger"
{
procedure LogDeletion(RecordID: RecordId; User: Code[50])
var
AuditEntry: Record "Audit Entry";
begin
AuditEntry.Init();
AuditEntry.EntryType := 'Deletion';
AuditEntry.RecordID := RecordID;
AuditEntry.UserID := User;
AuditEntry.Insert();
end;
}
- Subscribe to the Event:
codeunit 50106 "SalesOrderEvents"
{
[EventSubscriber(ObjectType::Table, Database::"Sales Header", 'OnAfterDeleteEvent', '', false, false)]
local procedure OnDeleteSalesOrder(var Rec: Record "Sales Header")
var
Logger: Codeunit "AuditLogger";
begin
Logger.LogDeletion(Rec.RecordId, UserId);
end;
}
By separating the "Logging" logic from the "Event" logic, we have created a system that is incredibly easy to maintain. If we decide to log to an external web service instead of a table, we only have to change the AuditLogger Codeunit, and the rest of our system remains untouched.
Not read yet
FAQ: Frequently Asked Questions
Q: Can I have multiple Codeunits for the same task? A: Yes, and often you should. If your logic is very complex, breaking it into smaller, specialized Codeunits is a great way to manage complexity.
Q: Should I put all my code in one large Codeunit to save space? A: Absolutely not. Large Codeunits ("God Objects") are difficult to read, test, and debug. Keep your Codeunits focused and small.
Q: How do I know when to use a Codeunit instead of a Table function? A: If the function relates strictly to a single record's data (like calculating a total for a specific row), it belongs in the Table. If the function interacts with other tables, external services, or performs a cross-record process, it belongs in a Codeunit.
Q: Are there any performance concerns with Codeunits?
A: Codeunits are very efficient. However, avoid passing massive datasets by value. Always pass by reference (var) if you are passing large records or lists.
Not read yet
Key Takeaways
- Centralization: Codeunits are the primary location for business logic in Business Central, allowing you to centralize code that is not tied to a specific UI or table.
- Modularity: Adhere to the Single Responsibility Principle. Each Codeunit should do one thing well. This makes your code cleaner and easier to maintain.
- Reusability: By making your procedures public, you allow other developers (or your own future self) to leverage your logic across different parts of the application.
- Stateless Design: Aim for stateless Codeunits that rely on parameters rather than persistent global variables. This reduces bugs and makes your code more predictable.
- Testing: Codeunits are the primary target for automated testing. Always write tests for your Codeunits to ensure they continue to work correctly as the system evolves.
- Interfaces: Use interfaces to decouple your implementation from your business logic, allowing for greater flexibility and easier system upgrades.
- Event Subscribers: Use Codeunits to house your event subscribers, keeping your event-driven code organized and separate from core business processes.
By mastering the creation and access of Codeunits, you are moving beyond simple data entry and into the realm of true application architecture. You are no longer just "making things work"; you are building a system that is resilient, scalable, and professional. Take the time to practice these patterns in your own development environment, and you will quickly see the benefits in the quality and maintainability of your code.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
Spend your points to unlock exam-style practice questions
Spend points to unlock MB-820 exam-style practice questions.
Practice for MB-820