AL Development Best Practices
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 9 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
AL Development Best Practices: Mastering Dynamics 365 Business Central
Introduction: Why AL Development Standards Matter
The Application Language (AL) is the primary engine behind Dynamics 365 Business Central. As developers, we are not just writing code; we are building business logic that dictates how organizations manage their finances, supply chains, and customer relationships. When you sit for the MB-820 exam, you are expected to demonstrate not just the ability to write code that compiles, but the ability to write code that is maintainable, scalable, and secure.
Poorly written AL code is a significant liability. It leads to performance bottlenecks, difficult upgrade paths, and brittle systems that break whenever a minor change is introduced. In a cloud-based environment like Business Central, where updates are frequent and automated, the quality of your extension determines whether your client’s business operations run smoothly or suffer from downtime and errors. This lesson explores the foundational and advanced best practices for AL development, ensuring you are prepared both for the certification exam and for real-world software delivery.
Not read yet
1. Structuring Your Project and Extension Design
The way you structure your AL project is the first step toward long-term success. A disorganized project leads to confusion, especially as an extension grows in complexity. You should always follow a modular approach, grouping related objects together and keeping your files organized logically.
The Importance of Naming Conventions
Naming conventions are the bedrock of readable code. While AL allows you to name objects almost anything, industry standards require a consistent approach. Every object (Table, Page, Codeunit) should have a prefix or suffix that identifies your specific extension or company. This prevents naming collisions when multiple extensions are installed in the same environment.
- Prefixing: Use a unique 3-4 character prefix for all custom objects (e.g.,
CRD_CustomerCardExt). - Logical Names: Avoid generic names like
MyTable. Instead, use descriptive names likeCRD_ProjectManagerSetup. - Casing: Use PascalCase for object names and functions, and camelCase for local variables.
Project Folder Structure
Visual Studio Code allows you to organize your workspace into folders. Do not dump every file into the root directory. Instead, create subfolders based on object type or functional area. A typical structure looks like this:
/Tables/Pages/Codeunits/Enums/Reports/Permissions
Callout: The "Single Responsibility" Principle The Single Responsibility Principle (SRP) states that a class or codeunit should have one, and only one, reason to change. If your codeunit handles both "Customer Validation" and "Posting Invoices," you have violated this principle. Break them apart into two separate codeunits. This makes testing easier and prevents a change in the invoicing logic from accidentally breaking your validation logic.
Not read yet
2. Writing Clean and Maintainable AL Code
Writing code that works is the bare minimum. Writing code that other developers can understand six months from now is the goal. AL is a high-level language, but it still requires careful attention to detail regarding variable declaration, scope, and formatting.
Variable Scope and Declaration
Variables should always be declared with the smallest possible scope. If a variable is only needed within a specific trigger, declare it as a local variable. Global variables should be used sparingly, as they persist for the entire duration of the object’s lifecycle and can lead to unexpected side effects if not cleared properly.
// Bad practice: Global variable used for a temporary calculation
var
TotalAmount: Decimal;
procedure CalculateTotal()
begin
TotalAmount := 500 + 200;
end;
// Good practice: Local variable limits scope and memory footprint
procedure CalculateTotal()
var
LocalTotal: Decimal;
begin
LocalTotal := 500 + 200;
end;
Avoiding "Hard-Coding"
Hard-coding values like IDs, strings, or specific folder paths is a recipe for disaster. If a value might change, it should be stored in a setup table or a constant. For example, never hard-code a G/L Account number. Instead, allow the user to select the account in a setup page and retrieve that value using a Record.Get call.
Tip: Use Labels for User-Facing Strings Never use hard-coded strings in error messages or UI elements. Use the
Labeldata type. Labels allow for translation files (.xlf) to handle multi-language support, ensuring your application is ready for global use without code changes.
Not read yet
3. Performance Optimization Techniques
Performance is critical in Business Central. Because the platform runs in the cloud and shares resources, inefficient code can lead to "throttling" or slow experiences for the end-user.
Efficient Data Access
The most common performance killer in AL is the improper use of FIND and SETFILTER statements. Avoid loops that perform database queries inside them. If you need to process a large set of records, use the SetLoadFields function to load only the fields you actually need.
// Efficient data retrieval
procedure GetCustomerBalance(CustNo: Code[20]): Decimal
var
Customer: Record Customer;
begin
Customer.SetLoadFields(Balance); // Only retrieve the Balance field
if Customer.Get(CustNo) then
exit(Customer.Balance);
end;
Table Indexing
When you create new tables, carefully consider your keys. If you frequently filter a table by a specific field, ensure that field is part of a key. However, do not over-index, as every index adds overhead to insert and update operations. A good rule of thumb is to index only what is necessary for frequent lookups and sorting.
Warning: The "Hidden" Loop Be careful with
TableRelationproperties andOnLookuptriggers. Sometimes, simply opening a page can trigger complex calculations or data lookups that run for every record in a list. Always profile your code using the "AL Profiler" tool in VS Code to identify where your performance bottlenecks actually reside.
Not read yet
4. Error Handling and User Experience
A robust application handles errors gracefully. Instead of letting the system crash or show a cryptic error message, provide clear, actionable feedback to the user.
Using Error Handling
Use the Error() function only for critical stops where the process cannot continue. For warnings or informational messages, consider using Message() or Notification. When an error is raised, provide a clear explanation of why it happened and how the user can fix it.
if (Quantity < 0) then
Error('The quantity cannot be negative. Please enter a value greater than or equal to zero.');
The Power of Notifications
Notifications are a non-intrusive way to guide users. Unlike errors, which stop the process, notifications appear in the UI and allow the user to choose an action. This is excellent for suggesting corrections or providing helpful tips during data entry.
5. Security Best Practices
Security is not an afterthought; it is integrated into every line of code you write. In Business Central, you must ensure that your code respects the permissions assigned to the user.
Permissions and Codeunits
Always design your code to run under the user's permissions, not the "Super" user permissions, unless absolutely necessary. If you must perform an action that the user doesn't have permissions for, use a Codeunit with the PermissionsTable property or set the Permissions property to allow specific access.
Input Validation
Never trust user input. Whether it is a text box, an API call, or an uploaded file, always validate the data. If a user enters a date, check if it is within a valid range. If they enter a code, check if it exists in the corresponding master table.
| Security Feature | Purpose |
|---|---|
| Permissions | Restricts access to specific tables and objects. |
| Input Validation | Prevents malicious or malformed data from entering the database. |
| API Authentication | Ensures that external integrations are secure and authorized. |
| Data Privacy | Ensures sensitive fields are hidden or masked based on user roles. |
Not read yet
6. Testing and Debugging
You cannot guarantee the quality of your code without a rigorous testing strategy. The MB-820 exam emphasizes the importance of automated testing.
Automated Tests
The TestRunner codeunit is the standard for automated testing in Business Central. You should write tests for every major piece of business logic. A good test should be isolated, repeatable, and fast.
- Arrange: Set up the test data.
- Act: Execute the function you are testing.
- Assert: Verify that the result matches your expectation.
The Debugger
The VS Code debugger is your best friend. Learn how to set breakpoints, inspect variables, and step through code line-by-line. If you are struggling with a complex logic flow, don't guess—debug.
Callout: Test-Driven Development (TDD) Consider practicing TDD. In TDD, you write the test before you write the code. This forces you to think about the requirements and the desired outcome before you even begin development. It results in cleaner, more modular code because you are designing it to be testable from the start.
Not read yet
7. Common Pitfalls to Avoid
Even experienced developers fall into certain traps. Being aware of these will save you hours of troubleshooting.
- Ignoring the
OnInsertandOnModifytriggers: Sometimes developers forget that standard Business Central logic lives in these triggers. If you write your own logic, ensure you aren't bypassing standard validation. - Over-complicating extensions: Keep your extensions focused. If you find yourself changing standard tables in fundamental ways, consider if there is a better way to achieve your goal using Events or Table Extensions.
- Not using Events: Always prefer Events over modifying standard code. Modifying the base application directly makes your solution impossible to upgrade. If you need a hook into a standard process, look for the appropriate
IntegrationEventorBusinessEvent. - Hard-coding IDs: As mentioned earlier, never use hard-coded IDs. Use Table IDs or Field IDs via symbols or references.
Not read yet
8. Step-by-Step: Creating a Best-Practice Extension
To summarize everything we have discussed, let's look at the process of creating a simple extension that follows these standards.
- Requirement Analysis: Determine exactly what the business problem is.
- Object Design: Create the necessary objects (e.g., a setup table and a page to manage it). Use a unique prefix for all names.
- Code Implementation:
- Write the logic in a Codeunit, not on the page.
- Use local variables for everything except what must be global.
- Implement validation logic to handle errors gracefully.
- Security Review: Ensure that the user permissions are set correctly.
- Testing: Create a
TestRunnercodeunit to verify the logic. - Documentation: Add comments to your code using the
///syntax for IntelliSense documentation.
/// <summary>
/// Calculates the tax amount based on the provided total.
/// </summary>
/// <param name="Total">The total amount.</param>
/// <returns>The calculated tax.</returns>
procedure CalculateTax(Total: Decimal): Decimal
var
TaxRate: Decimal;
begin
TaxRate := 0.05; // Ideally, retrieve this from a setup table
exit(Total * TaxRate);
end;
Not read yet
Frequently Asked Questions (FAQ)
Q: Should I put all my code in one large codeunit? A: Absolutely not. Large codeunits are difficult to read, test, and maintain. Break your logic into smaller, focused codeunits based on the functionality they provide.
Q: Is it okay to use Global variables in pages?
A: In pages, global variables are often necessary to store state between triggers. However, keep them to a minimum and ensure they are reset when the page closes or the record changes if they are no longer needed.
Q: How do I know which events to use? A: Use the "Event Recorder" in Business Central to see which events are triggered when you perform a specific action in the UI. This is the most reliable way to find the correct hook point for your extension.
Key Takeaways for MB-820 Success
- Consistency is King: Always follow a strict naming convention and project structure. It makes your code professional and easy to navigate for other team members.
- Performance Matters: Avoid unnecessary database calls. Use
SetLoadFieldsand be mindful of your loops. A slow application is a failed application. - Prioritize Maintainability: Use the Single Responsibility Principle. Write small, testable functions and avoid hard-coding values or IDs.
- Embrace Events: Never modify base application code directly. Use
TableExtensionsandEventsto extend functionality, ensuring your code remains compatible with future upgrades. - Automate Your Testing: Use
TestRunnercodeunits to create a suite of automated tests. This is not optional—it is a requirement for modern, high-quality development. - Security First: Always validate user input and ensure your code respects the user's permission set. Security should be baked into your development process, not added at the end.
- Document as You Go: Use XML comments (
///) for your procedures. This ensures that when you or someone else uses your code later, IntelliSense will provide helpful documentation.
By adhering to these practices, you demonstrate that you are not just a coder, but a professional developer capable of building high-quality, sustainable solutions within the Dynamics 365 Business Central ecosystem. Good luck with your exam preparation—focus on the why behind these practices, as the MB-820 exam often tests your ability to choose the "best" solution among several technically correct options.
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