Working with Interfaces in AL
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 13 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Working with Interfaces in AL
Introduction: The Power of Abstraction in AL
In the context of Microsoft Dynamics 365 Business Central development, the AL (Application Language) environment has evolved significantly over the years. One of the most powerful additions to the language is the concept of the interface. If you come from a background in C#, Java, or other object-oriented languages, you are likely already familiar with the concept of a contract that defines what a class must do, without mandating how it must do it. In AL, interfaces serve the exact same purpose: they allow you to define a set of methods that different objects must implement, providing a mechanism for loose coupling and polymorphism.
Why does this matter for your development workflow? As your Business Central solutions grow in size and complexity, maintaining rigid, tightly coupled code becomes an enormous burden. When one part of your code depends directly on the implementation details of another, any change in that implementation can cause a ripple effect of errors throughout your entire project. Interfaces solve this by acting as a buffer. By programming against an interface rather than a concrete implementation, you make your code modular, easier to test, and significantly more flexible. This lesson will guide you through the technical implementation of interfaces, best practices for their use, and how to refactor your existing code to take advantage of this modern design pattern.
Not read yet
Understanding the Interface Concept
An interface in AL is a special type of object that defines a contract. It does not contain any executable code, nor does it contain any variables or data storage. It is purely a declaration of method signatures. When a codeunit implements an interface, it is essentially signing a legal document that states, "I promise to provide the logic for every method defined in this interface."
The primary benefit here is polymorphism. You can have multiple different codeunits that all implement the same interface, but each performs a different underlying task. For example, consider an interface called ICalculator with a method CalculateTax. You could have one implementation for US tax, another for EU VAT, and a third for a custom local tax. Because all three implement ICalculator, the rest of your application does not need to know which specific codeunit it is calling. It simply calls CalculateTax, and the platform handles the execution of the specific logic provided by the assigned implementation.
Callout: Interfaces vs. Codeunits An interface is not an object that runs; it is a blueprint. A codeunit is an object that contains executable code and can hold state (variables). You cannot call an interface directly; you must assign a codeunit that implements that interface to an interface variable, and then invoke the methods through that variable. Think of the interface as a remote control, and the codeunit as the device it controls.
Not read yet
Defining Your First Interface
Defining an interface in AL is straightforward. You create a new file with the .al extension and use the interface keyword. Unlike tables or pages, the interface file is very concise because it only contains procedure signatures.
Example: Defining an Interface
Let's define an interface for a shipping rate calculator. We want to ensure that any shipping provider we add to our system provides a way to calculate the cost and get a tracking link.
interface "IShippingProvider"
{
procedure GetShippingCost(Weight: Decimal; Destination: Code[20]): Decimal;
procedure GetTrackingLink(PackageId: Code[20]): Text;
}
In this example, the interface IShippingProvider requires two procedures. Any codeunit that implements this interface must include these two methods with the exact same signatures—meaning the same parameters, the same parameter types, and the same return types. If the signatures do not match, the compiler will throw an error, preventing you from building the app.
Not read yet
Implementing the Interface
Once you have defined your interface, you must create one or more codeunits to implement it. To tell the compiler that a codeunit is fulfilling the contract of an interface, you use the implements keyword in the codeunit definition.
Example: Implementing the Interface
Let's create a codeunit for a specific shipping provider, such as "FedEx".
codeunit 50100 "FedExProvider" implements "IShippingProvider"
{
procedure GetShippingCost(Weight: Decimal; Destination: Code[20]): Decimal;
begin
// Logic specific to FedEx
exit(Weight * 1.5);
end;
procedure GetTrackingLink(PackageId: Code[20]): Text;
begin
exit('https://www.fedex.com/track/' + PackageId);
end;
}
If you were to create another codeunit called UPSProvider, you would repeat the process, using the same implements "IShippingProvider" clause. This ensures that both codeunits are interchangeable from the perspective of any logic that relies on the IShippingProvider interface.
Not read yet
Using Interfaces in Application Logic
The true power of interfaces appears when you use them in your business logic. Instead of declaring a variable as a specific codeunit (e.g., var FedEx: Codeunit "FedExProvider"), you declare it as the interface type. This allows you to swap implementations at runtime.
Step-by-Step: Dynamic Implementation Assignment
- Declare the variable: Define a variable using the interface name.
- Assign the implementation: Use a codeunit that implements the interface.
- Call the methods: Execute the interface methods.
procedure CalculateShipping(ProviderCode: Code[20]; Weight: Decimal)
var
ShippingProvider: Interface "IShippingProvider";
begin
case ProviderCode of
'FEDEX':
ShippingProvider := Codeunit::"FedExProvider";
'UPS':
ShippingProvider := Codeunit::"UPSProvider";
else
Error('Provider not supported.');
end;
Message('Cost is %1', ShippingProvider.GetShippingCost(Weight, 'US'));
end;
This approach allows your CalculateShipping procedure to remain clean and extensible. If you add a new shipping provider in the future, you only need to create the new codeunit and add one line to the case statement. You do not need to modify the core logic of the CalculateShipping procedure itself.
Callout: Dependency Injection and Interfaces Interfaces are the foundation of Dependency Injection (DI) in AL. By using interfaces, you decouple the "what" from the "how." This makes it possible to write unit tests where you inject a "Mock" implementation of an interface instead of the "Real" production code, allowing you to test your logic without triggering external web services or writing to the database.
Not read yet
Best Practices for Interface Design
When designing interfaces, keep in mind that they are meant to be contracts that rarely change. Once an interface is published and used in other modules or extensions, changing the signature of a method (e.g., adding a parameter) will break all implementing codeunits.
1. Keep Interfaces Granular
Do not create "God Interfaces" that include dozens of methods. Instead, follow the Interface Segregation Principle. If a class only needs to calculate shipping, it shouldn't be forced to implement a method for printing labels or managing warehouse inventory. Create smaller, focused interfaces like IShippingCalculator and ILabelPrinter rather than one giant ILogistics interface.
2. Use Meaningful Naming Conventions
Prefix your interface names with an I (e.g., IProcessOrder, IPaymentGateway). This is a common industry standard that helps developers immediately identify that a specific type is an interface rather than a concrete class.
3. Document the Contract
Since interfaces don't contain implementation logic, the only way a developer knows what a method should do is through comments and documentation. Use XML comments above your procedure signatures to explain the expected behavior, constraints, and side effects.
4. Versioning Considerations
Because interfaces act as public APIs for your code, treat them with the same caution you would use for a public web service. If you absolutely must change a signature, consider creating a new version of the interface (e.g., IShippingProvider2) rather than modifying the original, to maintain backward compatibility.
Not read yet
Common Pitfalls and How to Avoid Them
Pitfall 1: Over-Engineering
Developers often fall into the trap of using interfaces for everything. Do not create an interface for every single codeunit in your application. If a codeunit is only ever used in one place and there is no intention of ever having multiple implementations, an interface just adds unnecessary complexity. Use interfaces only when you have a clear need for polymorphism or loose coupling.
Pitfall 2: Logic in the Interface
A common mistake is trying to put logic into the interface itself. Remember, an interface is just a declaration. If you find yourself needing to share logic across multiple implementations, do not try to hack it into the interface. Instead, use a base codeunit or a helper codeunit that the various implementations can call internally.
Pitfall 3: Ignoring Error Handling
When invoking an interface method, you are calling an implementation that might be provided by a third-party extension. Always assume that the implementation might fail. Implement robust error handling (using try-catch blocks or LastError checks) in the calling code to ensure that one faulty implementation doesn't crash your entire process.
Not read yet
Comparison: Interfaces vs. Codeunit Inheritance (The "Old Way")
Before interfaces were introduced in AL, developers often relied on "codeunit inheritance" patterns, which involved passing codeunits as parameters or using RunObject.
| Feature | Interface Pattern | Legacy Pattern (Direct References) |
|---|---|---|
| Coupling | Loose (Depends on contract) | Tight (Depends on concrete object) |
| Polymorphism | Built-in | Manual/Complex |
| Compiler Safety | High (Enforced signatures) | Low (Risky runtime calls) |
| Extensibility | High (Easily add new implementations) | Low (Requires modifying existing code) |
| Testing | Excellent (Easy to mock) | Difficult (Often requires real data) |
As shown in the table above, the Interface pattern is superior for modern, scalable, and testable application development. The legacy pattern often led to "spaghetti code" where a single codeunit contained nested if statements checking for different scenarios, making it impossible to manage as the number of variations grew.
Not read yet
Practical Application: Implementing a Plugin System
To fully grasp the power of interfaces, let's build a mini-plugin system. Imagine you are building a document processing engine for Business Central, and you want users to be able to add custom document "formatters" without modifying your core code.
Step 1: Define the Interface
interface "IDocumentFormatter"
{
procedure Format(var DocumentText: Text): Boolean;
}
Step 2: Create a Default Implementation
codeunit 50101 "DefaultFormatter" implements "IDocumentFormatter"
{
procedure Format(var DocumentText: Text): Boolean;
begin
DocumentText := UpperCase(DocumentText);
exit(true);
end;
}
Step 3: Create the Engine
The engine will look for all implementations of the interface. Note that you can also use Table data to dynamically map codes to implementations, which is a common pattern in Business Central when using the Interface type as a field in a table.
table 50102 "FormatterMapping"
{
fields
{
field(1; "Code"; Code[20]) { }
field(2; "Implementation"; Interface "IDocumentFormatter") { }
}
}
By storing the interface in a table field, you can allow users to choose which implementation to use in a setup page. When the user selects a formatter, the platform handles the connection between the record and the codeunit automatically. This is a highly advanced, professional way to build extensible software.
Warning: Be careful when using interfaces stored in table fields. If the codeunit that implements the interface is removed from the system or renamed, the reference in the database will become invalid. Always ensure that your deployment process accounts for these dependencies.
Not read yet
Testing and Mocking with Interfaces
Testing is where the value of interfaces becomes immediately apparent. When you have code that calls an external service (like a shipping API), you don't want your automated tests to actually call that service every time. It's slow, expensive, and unreliable.
With interfaces, you can create a "Mock" codeunit for your test.
Example: Mocking for Tests
codeunit 50105 "MockShippingProvider" implements "IShippingProvider"
{
procedure GetShippingCost(Weight: Decimal; Destination: Code[20]): Decimal;
begin
// Return a fixed value for testing purposes
exit(10.0);
end;
procedure GetTrackingLink(PackageId: Code[20]): Text;
begin
exit('http://mock-link.com');
end;
}
In your test codeunit, you can instantiate this MockShippingProvider and pass it into your logic. This allows you to verify that your business logic handles the returned values correctly without ever needing to communicate with the real FedEx or UPS servers. This is the gold standard for unit testing in Business Central.
Not read yet
Managing Interface Visibility
By default, objects in AL are often internal to an extension. If you want your interface to be available to other extensions (so that other developers can write their own implementations), you must set the Access property of the interface to Public.
interface "IPublicService"
{
Access = Public;
procedure Execute();
}
If you do not set the Access property, the interface is treated as Internal. This is a great way to hide your implementation details and keep your API clean. Only expose what you intend for other developers to use.
Deep Dive: The Interface Type in Variables
You might have noticed that you can use the interface type directly as a variable. This variable acts as a container for any object that implements that interface.
Understanding Assignment
When you assign a codeunit to an interface variable, the platform checks if the codeunit implements the interface. If it does not, the compiler throws an error. This is a compile-time check, which is much safer than the old RunObject or Invoke methods that often failed at runtime.
var
MyInterface: Interface "IShippingProvider";
MyCodeunit: Codeunit "FedExProvider";
begin
// This is valid
MyInterface := MyCodeunit;
// This will cause a compiler error if "OtherCodeunit"
// does not implement "IShippingProvider"
// MyInterface := Codeunit::"OtherCodeunit";
end;
This ensures that your code is type-safe. You never have to worry about calling a method that doesn't exist, provided the compiler is happy. This eliminates an entire class of runtime bugs.
Not read yet
Summary of Key Takeaways
To recap, mastering interfaces in AL is a journey from writing procedural, monolithic code to building modern, modular, and extensible solutions. Here are the essential points to remember:
- Interfaces as Contracts: Use interfaces to define a contract of methods that must be implemented. They focus on the "what" rather than the "how."
- Polymorphism: Interfaces allow you to swap implementation logic at runtime, making your code significantly more flexible for different business scenarios.
- Loose Coupling: By programming against an interface instead of a concrete codeunit, you reduce the dependencies in your code, making it easier to maintain and refactor.
- Testing Efficiency: Interfaces are the secret weapon for unit testing. By creating mock implementations, you can test your business logic in isolation without external dependencies.
- Compiler Enforcement: The AL compiler ensures that any codeunit assigned to an interface actually implements the required methods, providing a robust safety net during development.
- Granular Design: Follow the Interface Segregation Principle—create smaller, specific interfaces rather than large, bloated ones to keep your code manageable.
- Public vs. Internal: Use the
Accessproperty to control whether your interface is visible to other extensions, ensuring you only expose the APIs you want to support long-term.
By consistently applying these principles, you will find that your Business Central solutions become easier to write, easier to test, and—most importantly—much easier to maintain as requirements change over time. Start by identifying one area in your current project where you have a case statement switching between different codeunits, and refactor that into an interface-based design. You will immediately see the reduction in complexity.
Not read yet
Frequently Asked Questions (FAQ)
Can an interface contain variables?
No. An interface is strictly a definition of procedures. It cannot contain variables, constants, or data storage of any kind. If you need to share data, pass that data as parameters to the interface methods.
Can a codeunit implement multiple interfaces?
Yes, absolutely. A codeunit can implement as many interfaces as you need. This is a great way to create a "Swiss Army Knife" codeunit that fulfills multiple roles, provided those roles are distinct and well-defined. You simply list them in the implements clause separated by commas: implements "IInterfaceA", "IInterfaceB".
What happens if I rename a method in an interface?
If you rename a method in an interface, you must update all codeunits that implement that interface. If you don't, the compiler will report that those codeunits no longer satisfy the interface contract. This is why it is critical to get your interface design right early on.
Is there a performance penalty for using interfaces?
The performance overhead of using an interface is negligible in almost all Business Central use cases. The platform handles the dispatching of calls efficiently. The benefits in maintainability and code quality far outweigh any theoretical performance cost.
Can I use interfaces in table extensions?
You can use an interface type as a field in a table, as demonstrated in the plugin example. This is a very powerful way to allow configuration-driven behavior in your applications. Just be aware of the dependency management required when deploying such extensions.
Final Thoughts on Future-Proofing
As the Business Central ecosystem continues to move toward a cloud-first, extension-based model, the ability to write modular code is no longer optional—it is a requirement for survival. When you build with interfaces, you are creating an "open" system that can be extended by others without requiring you to change your source code. This is the essence of a healthy, long-term software ecosystem.
Whenever you are about to write a new feature, ask yourself: "Will I ever need to change how this works in the future?" If the answer is yes, or if you think a customer might want to swap out your logic for their own, an interface is likely the right tool for the job. It puts the power of abstraction in your hands, allowing you to build the next generation of Business Central extensions with confidence and clarity.
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