Creating Custom Procedures
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
Mastering Custom Procedures in AL: Extending Dynamics 365 Business Central
Introduction: The Power of Custom Procedures
When developing for Dynamics 365 Business Central using the AL (Application Language) environment, you are essentially building upon a massive, pre-existing framework of business logic. While Microsoft provides thousands of standard functions, every organization eventually encounters a unique business requirement that cannot be solved by out-of-the-box features. This is where custom procedures become the backbone of your development work.
A procedure in AL is a block of code designed to perform a specific task. By encapsulating logic within these procedures, you move away from writing "spaghetti code"—long, unmanageable scripts—and instead create modular, reusable, and testable components. Understanding how to define, call, and scope these procedures is the single most important skill for a Business Central developer. It determines whether your code will be maintainable for years to come or if it will become a technical debt nightmare that breaks every time the platform updates.
In this lesson, we will explore the mechanics of creating custom procedures, the importance of parameter passing, the difference between local and global scope, and how to write clean, defensive code. Whether you are automating a simple calculation or building a complex integration with an external API, the principles covered here will provide the foundation you need to succeed.
Not read yet
Understanding the Anatomy of an AL Procedure
At its core, a procedure is a named section of code that can be executed from elsewhere in your application. Every procedure in AL is defined by a specific syntax that includes the procedure keyword, a name, parameters (optional), a return type (optional), and the logic block itself.
The Basic Syntax
To define a procedure, you must place it within an object (like a Table, Page, or Codeunit). The structure looks like this:
procedure MyProcedureName(ParameterName: DataType) : ReturnDataType
var
MyVariable: Integer;
begin
// Your business logic goes here
end;
When you look at this structure, notice the distinct parts. The procedure keyword signals the compiler that a new block of logic is starting. The name should always be descriptive—if your procedure calculates tax, call it CalculateTax, not DoSomething. The parameters define what information the procedure needs to do its job, and the return type specifies what the procedure gives back to the caller.
Callout: The Importance of Descriptive Naming In AL, you are often working within large teams or maintaining code written years ago. A procedure named
ProcessDatatells the next developer absolutely nothing about what the code actually does. A procedure namedValidateCustomerCreditLimitprovides immediate context, reducing the time spent reading the internal logic just to understand the intent. Always prioritize clarity over brevity.
Not read yet
Scope: Global vs. Local Procedures
One of the most common mistakes beginners make is failing to understand the scope of their procedures. Scope determines where your procedure can be accessed from. In AL, we differentiate between local and global procedures using the local keyword.
Local Procedures
A local procedure can only be called from within the same object where it is defined. If you have a complex calculation that is only relevant to a specific page—for example, a logic block that refreshes a specific UI element—you should mark it as local. This hides the procedure from other objects, which keeps your object's interface clean and prevents other developers from accidentally calling internal logic that might not be intended for external use.
local procedure CalculateInternalDiscount(Amount: Decimal) : Decimal
begin
exit(Amount * 0.05);
end;
Global Procedures
If you omit the local keyword, the procedure is global by default. This means any other object in your extension (or even objects in other extensions that depend on yours) can call this procedure. This is how you build an API for your own code. Use global procedures when you have logic that needs to be shared, such as a function to format a custom address string or a utility to log audit data.
Note: Always default to making your procedures
local. Only promote them to global status if you have a specific, documented reason for another object to access that functionality. This principle of "least privilege" is a cornerstone of clean software architecture.
Not read yet
Passing Parameters: By Value vs. By Reference
When you pass data into a procedure, you have two primary ways to do it: by value or by reference. Understanding the difference is vital for performance and for controlling how your data is modified.
Passing by Value
This is the default behavior. When you pass a variable by value, the procedure receives a copy of the data. If the procedure changes that value, the original variable in the calling code remains unchanged. This is safer for simple data types like integers, dates, or small strings.
Passing by Reference
When you use the var keyword in a parameter definition, you are passing the memory address of the variable. Any changes made to that variable inside the procedure will directly affect the original variable in the calling code. This is essential when you need to update a record or a large object without the overhead of copying the entire dataset.
// Passing by value (Default)
procedure IncrementValue(Value: Integer)
begin
Value += 1;
end;
// Passing by reference (Using var)
procedure IncrementRecordCount(var Count: Integer)
begin
Count += 1;
end;
Warning: Be extremely careful with
varparameters. While they are efficient, they can lead to "side effects" where your data changes in ways that are difficult to debug. Only usevarwhen you explicitly intend to modify the input variable.
Not read yet
Best Practices for Writing Clean Procedures
Writing a procedure is easy; writing a good procedure is an art. As you gain experience, you will notice that the most stable Business Central extensions are those that follow strict internal coding standards.
1. The Single Responsibility Principle
A procedure should do one thing and do it well. If you find yourself writing a procedure that calculates tax, updates the general ledger, sends an email, and prints a report, you have created a "God Procedure." This is difficult to test and impossible to reuse. Break that logic into four distinct procedures: CalculateTax, UpdateGL, SendEmail, and PrintReport.
2. Keep Procedures Short
There is no hard rule on line count, but as a general guideline, if a procedure exceeds 50 lines of code, it is likely doing too much. Long procedures are hard to read and often contain hidden logic branches that lead to bugs. If you find your procedure getting long, look for logical blocks that can be extracted into their own smaller, helper procedures.
3. Use Meaningful Parameter Names
Avoid single-letter variables like x, y, or z. Use descriptive names like SalesHeader, PostingDate, or CustomerNo. When a developer looks at your procedure signature, they should know exactly what is required without having to open the procedure body.
4. Defensive Programming
Always validate your inputs. If your procedure expects a CustomerNo, check if it is empty before proceeding. Use Error() or TestField() to stop execution if the data provided is invalid. This prevents your system from processing bad data and creating corrupted records.
| Best Practice | Benefit |
|---|---|
| Keep it Local | Reduces clutter and unintended dependencies. |
| Single Responsibility | Makes code easier to test and reuse. |
| Defensive Coding | Prevents data corruption and runtime errors. |
| Descriptive Naming | Improves readability and maintainability. |
Not read yet
Practical Example: Building a Discount Calculator
Let’s put these concepts into practice by building a library procedure for a Sales Order extension. Suppose we need a procedure that calculates a volume-based discount for customers.
The Code Implementation
codeunit 50100 "DiscountCalculator"
{
// This procedure is global because other pages might need it
procedure CalculateVolumeDiscount(OrderAmount: Decimal; CustomerLevel: Option Bronze, Silver, Gold) : Decimal
var
DiscountRate: Decimal;
begin
// Validate input
if OrderAmount <= 0 then
exit(0);
// Determine discount based on level
case CustomerLevel of
CustomerLevel::Bronze:
DiscountRate := 0.02;
CustomerLevel::Silver:
DiscountRate := 0.05;
CustomerLevel::Gold:
DiscountRate := 0.10;
end;
exit(OrderAmount * DiscountRate);
end;
}
Explanation of the Example
In this code, we have created a Codeunit to act as a container for our logic. The procedure CalculateVolumeDiscount takes two parameters: an OrderAmount and a CustomerLevel. It returns a Decimal representing the calculated discount.
Notice the use of the case statement, which is cleaner than multiple if-then-else blocks. We also included a basic validation check: if the OrderAmount is zero or less, we immediately exit the procedure and return zero. This prevents the logic from running unnecessary calculations on invalid data.
Not read yet
Handling Records in Procedures
One of the most frequent tasks in Business Central is passing records (like Sales Header or Customer) to procedures. Because records can contain a massive amount of data, you should almost always pass them by reference using the var keyword.
Example: Updating a Record
Imagine you have a procedure that applies a standard formatting to a customer's address fields.
procedure FormatCustomerAddress(var Customer: Record Customer)
begin
Customer.Name := UpperCase(Customer.Name);
Customer.City := UpperCase(Customer.City);
Customer.Modify();
end;
By passing the Customer record as var, we are allowing the procedure to modify the specific record instance that was passed to it. When Customer.Modify() is called inside the procedure, it updates the record in the database. This is a powerful pattern, but remember that it makes the procedure dependent on the state of the record.
Tip: When passing records to procedures, ensure that the record is already "found" or "initialized" before passing it. If you pass an empty record to a procedure that expects data, you will likely trigger a runtime error.
Not read yet
Common Pitfalls and How to Avoid Them
Even experienced developers fall into traps when writing procedures. Here are the most common mistakes and how to steer clear of them.
1. Hardcoding Values
Avoid putting hardcoded values (like tax rates or IDs) directly into your procedure logic. Instead, define them as constants at the top of your object or retrieve them from a setup table. If the tax rate changes, you don’t want to hunt through your code to find every instance of 0.05 to update it.
2. Ignoring Return Values
If your procedure is designed to return a value, ensure that the calling code actually checks that value. A common bug occurs when a developer calls a procedure, assumes it succeeded, but the procedure actually failed or returned a default value because of an error condition.
3. Excessive Global Variable Usage
Some developers create procedures that rely heavily on global variables defined at the top of the codeunit. This makes the procedure "stateful," meaning it behaves differently depending on what happened earlier in the session. This is a recipe for unpredictable bugs. Try to make your procedures "pure" whenever possible—meaning they rely only on the parameters passed into them.
4. Over-complicating Logic
If you find yourself using nested if statements three or four levels deep, stop. You need to refactor. Use guard clauses (checking for errors early and exiting) to flatten your code structure.
// Bad: Deeply nested
procedure Process(Value: Integer)
begin
if Value > 0 then begin
if Value < 100 then begin
// Do work
end;
end;
end;
// Good: Guard clauses
procedure Process(Value: Integer)
begin
if (Value <= 0) or (Value >= 100) then
exit;
// Do work
end;
Not read yet
Error Handling within Procedures
Procedures often interact with the database, and database operations can fail. You must decide how your procedure handles errors. In Business Central, the Error() function halts execution and rolls back changes. This is appropriate for critical failures. However, sometimes you want your procedure to report a status rather than crash the system.
You can use a boolean return type to indicate success or failure.
procedure ValidateAndPost(var SalesHeader: Record "Sales Header") : Boolean
begin
if SalesHeader.Status <> SalesHeader.Status::Released then begin
Message('Order must be released before posting.');
exit(false);
end;
// Perform posting...
exit(true);
end;
This approach allows the calling page to decide how to handle the failure (e.g., by showing a message or logging the event) without the entire session terminating.
Advanced Procedure Concepts: Overloading and Events
As you advance, you will encounter two more concepts: Procedure Overloading and Event Subscribers.
Procedure Overloading
AL supports procedure overloading, which means you can have multiple procedures with the same name, provided they have different parameter signatures (different types or number of parameters). This is useful when you want to provide different ways to call the same logical function.
procedure FormatName(Name: Text) : Text
begin
exit(UpperCase(Name));
end;
procedure FormatName(FirstName: Text; LastName: Text) : Text
begin
exit(UpperCase(FirstName + ' ' + LastName));
end;
Event Subscribers
While not strictly "custom procedures" in the sense of defining them yourself, you will frequently write procedures that act as "event subscribers." These are procedures that listen for actions occurring in the base application (like "OnBeforePostSalesDoc"). When you write these, the same rules of clean, modular, and local code apply. Treat your event subscribers as entry points that immediately call other, well-structured custom procedures.
Not read yet
Troubleshooting and Debugging Procedures
When a custom procedure isn't working as expected, the Business Central debugger is your best friend. Follow these steps to diagnose issues:
- Set Breakpoints: Place a breakpoint at the start of your procedure.
- Step Through: Use the "Step Over" function to watch how variables change line by line.
- Inspect Variables: Hover over variables to see their current values. If a variable is not what you expect, trace back to where it was assigned.
- Check Call Stack: Use the call stack window to see which procedure called the current one. This helps you understand the sequence of events that led to the error.
Tip: If you are debugging a complex procedure, add temporary
Message()calls to log the state of variables. While the debugger is superior, sometimes a simple message log is faster for quick sanity checks during development.
Summary of Best Practices
To ensure your code remains professional and maintainable, keep these industry standards in mind:
- Modularity: Keep procedures focused on one specific task.
- Encapsulation: Use
localby default to protect your internal logic. - Parameter Safety: Use
varonly when modification is required; otherwise, pass by value. - Validation: Always validate inputs at the beginning of the procedure.
- Documentation: If a procedure is complex, add a comment explaining the "why" behind the logic, not just the "how."
- Consistency: Follow the naming conventions used by Microsoft in the base application (e.g., PascalCase for procedure names).
Not read yet
Key Takeaways
- Procedures are the building blocks of AL: They allow you to encapsulate logic, making your code modular, readable, and reusable.
- Scope is critical: Always default to
localscope to prevent unintended access to your code from other objects, reducing the risk of bugs and keeping your interface clean. - Understand parameter passing: Use value-passing for safety with simple data types, and use
var(reference-passing) for performance and record updates. - Apply the Single Responsibility Principle: If a procedure is doing more than one thing, it is too complex. Break it down into smaller, helper procedures to improve testability.
- Defensive coding prevents failures: Always validate inputs at the start of your procedure to stop bad data from propagating through your system.
- Avoid side effects: Procedures that rely on global variables are harder to debug and prone to unpredictable behavior; aim for "pure" procedures that rely only on their input parameters.
- Maintainability is the ultimate goal: Write your code for the person who will have to fix it in two years. Clear names, short procedures, and logical flow are more important than clever, one-line hacks.
By mastering these techniques, you move from being a developer who "makes things work" to a developer who creates robust, professional-grade Business Central solutions. Take the time to practice these patterns in your own development environment, and you will find that your development speed and the quality of your code improve significantly over time.
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