MSBA-352 · Lesson 9 of 12 · 20 min

Enums and interfaces

▶ Video coming soon A video version of this lesson is on the way.

The claim log was the last big piece of version 1, and it brought the first real design argument between Joss and Callum. A claim can end in three ways. A repair: Corbel & Finch sends a technician or ships replacement parts, and the cost is recovered from the manufacturer. A replacement: the café gets a new machine, the faulty one comes back to the QUARANTINE location, and the old registration is voided while the new machine gets its own. A refund: the café returns the machine and gets a credit memo. Each outcome needs different steps in Business Central. Joss's first draft was a single procedure with a large case statement. Noor looked at it and asked one question: "What happens when Callum adds a fourth outcome?" The answer led to enums and interfaces.

Enums

An enum is an object that defines a named list of values. A field of an enum type can hold only those values, shows them as a drop-down list to users, and stores them as integers in the database. Enums replaced the older Option data type, which defined values inline on a field and could not be extended by other apps.

The registration status enum.
namespace Quarrystone.CorbelFinch.Warranty;

enum 50100 "CNF Warranty Status"
{
    Extensible = false;
    Caption = 'Warranty Status';

    value(0; Active) { Caption = 'Active'; }
    value(1; Expired) { Caption = 'Expired'; }
    value(2; Void) { Caption = 'Void'; }
}

Each value has an ordinal, the integer stored in the database, a name used in code, and a caption shown to users and translated with the app's labels. Code refers to values as Status::Active or, from a record, Registration.Status::Active. The ordinal is permanent: once data is stored, changing which name belongs to ordinal 1 would silently change the meaning of every row.

The Extensible property decides whether other apps may add values. Status is not extensible. The code in this app makes decisions on status everywhere, and an unknown fourth status from another app would fall through every one of them. Noor's test was simple: if adding a value would require changes to code you own, the enum should not be extensible, or it should come with an interface, as the next section shows.

Working with enums in code

Common enum operations.
NeedAL
Compareif Registration.Status = Registration.Status::Void then
Branch on all valuescase Registration.Status of ... end
Show the captionFormat(Registration.Status)
Get the ordinalRegistration.Status.AsInteger()
Convert from an ordinalEnum::"CNF Warranty Status".FromInteger(2)
List all valuesEnum::"CNF Warranty Status".Ordinals() and .Names()

Enums work in table fields, variables, parameters and return values, and they appear in APIs as their names, which makes JSON easy to read. Standard Business Central uses hundreds of enums, many of them extensible: sales document types, item tracking types, payment methods. Partners add values with an enumextension, whose shape appears later in this lesson.

Noor warned against extending standard enums lightly. Adding a value to a standard enum means Microsoft's code will meet a value it was never written for. Some standard enums are designed for that and come with an interface that tells Microsoft's code what to do with the new value. Others are extensible only so partners can label things, and the base code ignores unknown values. Reading how the enum is used comes first.

The problem with a big case statement

Joss's first draft of the claim resolution looked like this in outline: one procedure, ResolveClaim, with a case on the claim's resolution type. Under Repair, it created a purchase invoice to the manufacturer for the parts and logged the technician's time. Under Replace, it created a sales order for a new machine at zero price, a return order for the faulty one to QUARANTINE, and voided the registration. Under Refund, it created a return order and a credit memo.

It worked, but every outcome lived in one place, and every new outcome meant editing that procedure, retesting all of it, and shipping a new version of the whole app. And there was a fourth outcome coming: Callum had mentioned a loaner program, where a café gets a temporary machine during a long repair. Quarrystone might build that as a separate app later. With a case statement, the loaner app would have to change the warranty app's code, which an extension cannot do.

Interfaces

An interface is an object that declares procedures without implementing them. Any codeunit can declare that it implements the interface, and must then provide every procedure with exactly the declared signature. Code that holds a variable of the interface type can call those procedures without knowing which codeunit is behind it.

An interface and two implementing codeunits.
namespace Quarrystone.CorbelFinch.Warranty;

interface "CNF Claim Resolution"
{
    procedure Validate(var Claim: Record "CNF Warranty Claim");
    procedure Resolve(var Claim: Record "CNF Warranty Claim");
    procedure VoidsRegistration(): Boolean;
}

codeunit 50120 "CNF Repair Resolution" implements "CNF Claim Resolution"
{
    procedure Validate(var Claim: Record "CNF Warranty Claim")
    begin
        Claim.TestField("Technician No.");
    end;

    procedure Resolve(var Claim: Record "CNF Warranty Claim")
    begin
        // Log technician time and create a purchase invoice to the manufacturer for parts.
    end;

    procedure VoidsRegistration(): Boolean
    begin
        exit(false);
    end;
}

codeunit 50121 "CNF Replace Resolution" implements "CNF Claim Resolution"
{
    procedure Validate(var Claim: Record "CNF Warranty Claim")
    begin
        Claim.TestField("Replacement Serial No.");
    end;

    procedure Resolve(var Claim: Record "CNF Warranty Claim")
    begin
        // Create a zero-price sales order for the new machine and a return order to QUARANTINE.
    end;

    procedure VoidsRegistration(): Boolean
    begin
        exit(true);
    end;
}

Each outcome now has its own codeunit, small enough to read in one screen and test on its own. The interface is a contract: Validate checks that the claim has what this outcome needs, Resolve does the work, and VoidsRegistration answers a question the common code needs to ask.

Connecting an enum to an interface

The remaining question is how the claim knows which codeunit to use. The answer is an enum that implements the interface. Each enum value names the codeunit that implements the interface for that value.

An extensible enum whose values each name an implementation.
enum 50101 "CNF Claim Resolution Type" implements "CNF Claim Resolution"
{
    Extensible = true;
    Caption = 'Claim Resolution Type';
    DefaultImplementation = "CNF Claim Resolution" = "CNF Repair Resolution";
    UnknownValueImplementation = "CNF Claim Resolution" = "CNF Unknown Resolution";

    value(0; Repair)
    {
        Caption = 'Repair';
        Implementation = "CNF Claim Resolution" = "CNF Repair Resolution";
    }
    value(1; Replace)
    {
        Caption = 'Replace';
        Implementation = "CNF Claim Resolution" = "CNF Replace Resolution";
    }
    value(2; Refund)
    {
        Caption = 'Refund';
        Implementation = "CNF Claim Resolution" = "CNF Refund Resolution";
    }
}

Now the claim table has a field Resolution Type of this enum, and the code that resolves a claim shrinks to a few lines with no case statement.

Resolving a claim through the interface.
    procedure ResolveClaim(var Claim: Record "CNF Warranty Claim")
    var
        Resolution: Interface "CNF Claim Resolution";
        Registration: Record "CNF Warranty Registration";
    begin
        Resolution := Claim."Resolution Type";
        Resolution.Validate(Claim);
        Resolution.Resolve(Claim);
        if Resolution.VoidsRegistration() then begin
            Registration.Get(Claim."Registration Entry No.");
            Registration.Status := Registration.Status::Void;
            Registration.Modify(true);
        end;
        Claim.Status := Claim.Status::Resolved;
        Claim.Modify(true);
    end;

Assigning an enum value to an interface variable picks the implementation named on that value. The common code (validate, resolve, void if needed, mark resolved) is written once and never changes when outcomes are added.

On the left, the enum CNF Claim Resolution Type with values Repair, Replace and Refund, plus a dashed value Loaner added by an enumextension in a separate app. Each value has an arrow to a codeunit: CNF Repair Resolution, CNF Replace Resolution, CNF Refund Resolution and, from the dashed value, a Loaner Resolution codeunit in the other app. All codeunits sit under a band labelled implements CNF Claim Resolution. On the right, ResolveClaim calls Validate, Resolve and VoidsRegistration on the interface.
Each enum value points to an implementation; another app can add a value and its implementation without changing this one.

Extending without editing

Because the enum is extensible, the future loaner app can add a value and its implementation from outside.

How a separate loaner app would add a fourth outcome.
enumextension 50300 "QBS Loaner Resolution" extends "CNF Claim Resolution Type"
{
    value(50300; Loaner)
    {
        Caption = 'Loaner during repair';
        Implementation = "CNF Claim Resolution" = "QBS Loaner Resolution";
    }
}

The warranty app's ResolveClaim procedure handles loaners without a single change. This is the main reason interfaces exist in AL: they let one app define a behaviour that other apps can supply, and they are how Microsoft makes many standard features pluggable, such as how price calculation works or how certain document types are handled.

Two properties guard the edges. DefaultImplementation is used for any value that does not name its own implementation, which saves repeating it. UnknownValueImplementation is used when the code meets a value whose app has been uninstalled, for example a claim stored with the Loaner value after the loaner app was removed. Joss's CNF Unknown Resolution codeunit raises a clear error telling the user the outcome's app is missing, instead of failing somewhere obscure.

When to use which

Choosing between enums, interfaces and events.
SituationUse
A fixed list of states the app controlsA non-extensible enum, like warranty status
A list other apps may label or add to, with no behaviour attachedAn extensible enum
A list where each value means different behaviourAn extensible enum that implements an interface
Several interchangeable implementations not tied to a listAn interface with codeunits chosen by setup or by code
A one-off variation in standard behaviourAn event subscriber (lesson 6)

Noor's summary for Joss: events let you react to someone else's code at a moment they chose; interfaces let others supply behaviour for a contract you defined. The warranty app uses both. It subscribes to Microsoft's posting event, and it offers its own interface for claim outcomes.

Worked problem

Adding an outcome

In spring 2027 Callum might want a fourth outcome, Credit only, where the café keeps the faulty machine and receives a partial credit memo. How is it added if it is built inside the warranty app, and how if it is built in a separate app?

Show solution
  1. Inside the warranty app: write a CNF Credit Resolution codeunit that implements CNF Claim Resolution, add value 3 to the enum naming it, and ship a new version.
  2. In a separate app: write the codeunit there, and add the value through an enumextension with an ordinal from that app's range.
  3. In both cases, ResolveClaim and the claim pages do not change; the new value appears in the Resolution Type drop-down.
  4. Test that Validate rejects a claim missing the credit amount, and that VoidsRegistration returns false, since the machine stays with the café.

Answer: Add an implementing codeunit and an enum value; the calling code stays the same.

Enums in pages, reports and APIs

Enums behave well everywhere. On a page, an enum field is a drop-down list of captions in the user's language. In a report, a column of an enum type shows the caption by default, and Format with a number can return the name or the ordinal instead. In an API page, an enum appears in JSON as the value's name, such as "Repair", which outside systems can read without a lookup table. Filters work on names too: a list page view filtered on Status = const(Active) keeps working even if captions are later translated, because the filter uses the name, not the caption. The one thing to avoid is storing an enum's caption in a Text field, which breaks as soon as anyone translates or rewords it.

Designing a good interface

An interface is a promise to every codeunit that implements it, including ones written by other teams years later. Noor gave Joss four guidelines. Keep it small: three procedures that every outcome needs, not ten that most outcomes leave empty. Pass records with var where an implementation might need to update them, so the contract does not have to change later. Name procedures after what they mean to the business, such as Resolve, rather than how today's implementation works. And never change a released interface: adding a procedure would break every implementation that does not have it. If the contract has to grow, declare a second interface and let codeunits implement both. Newer AL runtimes add features that help with this, and Joss was told to read the release notes before relying on any of them.

How Microsoft uses the same pattern

Joss was surprised to learn that the base application uses exactly this design for some of its own features. Price calculation in Business Central is selected through an enum whose values implement a price calculation interface, so a partner can supply a different calculation method without replacing Microsoft's code. Several other areas follow the same idea. Reading one of these in the base application source, through Go to Definition, is the best way to see how a large interface is structured, documented and versioned in practice, and Noor set it as reading for the week after the warranty review.

Testing implementations

Each implementing codeunit is small and can be tested on its own. Joss wrote one test case per outcome: Validate must reject a claim that lacks the outcome's required field, Resolve must create the expected documents, and VoidsRegistration must return the expected answer. Then one test of ResolveClaim with each enum value checks the wiring. When the loaner app arrives, its developer will only need tests for the new codeunit and one wiring test, because the existing ones keep proving that repair, replace and refund still work.

Enums or setup tables?

Not every list belongs in an enum. Enums suit lists whose values drive code: each value means the program does something different. Lists that users maintain, and whose values only label data, belong in a setup table with a page where an administrator can add and remove entries without a developer. Corbel & Finch's return reasons from the inventory course are a good example: DAMAGED, WRONG-ITEM, QUALITY and OVERSTOCK are rows in a standard table, not enum values, because Callum can add a reason any day. Joss applied the same test to claim fault categories, such as burrs, motor or electronics. They only label claims for Ysmay's analysis, so they became a small setup table, while resolution types, which drive code, stayed an enum.

Common mistakes

  • MistakeUsing the Option data type for new fields.

    InsteadUse an enum object so values have captions, can be reused and can be extended if needed.

  • MistakeMaking every enum extensible.

    InsteadMake an enum extensible only when unknown values cannot break your code, or when an interface handles them.

  • MistakeChanging the ordinal of an existing value.

    InsteadTreat ordinals as permanent once data exists.

  • MistakeHandling each outcome in a growing case statement.

    InsteadPut each outcome in a codeunit implementing an interface, selected by an enum value.

  • MistakeLeaving UnknownValueImplementation unset on an extensible enum with an interface.

    InsteadProvide a codeunit that fails clearly when the value's app is missing.

Summary and key terms

  • Enums define named lists of values with ordinals, names and captions, replacing Option fields.
  • Extensible enums can be extended with enumextension objects from other apps.
  • Interfaces declare procedures; codeunits implement them with matching signatures.
  • An enum can implement an interface, with each value naming its implementing codeunit.
  • Calling code assigns an enum value to an interface variable and calls procedures without a case statement.
  • DefaultImplementation and UnknownValueImplementation cover values without their own implementation and values from removed apps.
Enum
An object defining a named list of values stored as integers.
Ordinal
The integer that represents an enum value in the database.
Extensible
An enum property that allows other apps to add values.
Enum extension
An object that adds values to an extensible enum.
Interface
An object that declares procedures for codeunits to implement.
Implementation
The codeunit an enum value names for an interface.
UnknownValueImplementation
The implementation used for values whose defining app is not installed.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Why is the warranty status enum not extensible?

    Show answer

    The app makes decisions on status throughout its code, and an unknown status from another app would not be handled anywhere.

  2. What does Resolution := Claim."Resolution Type" do?

    Show answer

    It sets the interface variable to the codeunit that implements the interface for the claim's resolution type value.

  3. A claim was saved with value Loaner, and the loaner app was later uninstalled. What runs when the claim is resolved?

    Show answer

    The UnknownValueImplementation codeunit, which raises a clear error that the outcome's app is missing.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz