MSBA-341 · Lesson 3 of 12 · 19 min

Chain of command

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

With the fields in place, Marisol's real requirement came into view: a product receipt for a casting that needs a certificate must not post until the certificate is recorded or a waiver is approved. That is behaviour, not data, and it lives inside Microsoft's code. Desmond said the tool for changing behaviour inside a standard method is Chain of Command, usually shortened to CoC, and that it was the single most important extension technique on the MB-500 exam and in real projects. He also said it was the easiest one to misuse, so the session would spend as long on the rules as on the syntax.

The idea

Chain of Command lets an extension class wrap a public or protected method of a standard class, table, data entity or form. The wrapper has the same name and signature as the original. When anything calls the method, the runtime calls the wrappers first. Each wrapper must call next, which passes control along the chain to the next wrapper and finally to the original method. Code written before the next call runs before the standard logic; code written after it runs afterwards and can see and change the return value. Several models can wrap the same method, each adding its own logic, and none of them changes the original.

Four boxes in a row: caller validateWrite, wrapper in ISV model, wrapper in CobaltRidgeCustom and original PurchLine method. Black arrows labelled next run left to right between them; dashed gold arrows return right to left. Notes below say that code before next runs on the way in and code after next runs on the way out with the result, and that the order between wrappers in different models is not guaranteed, so no wrapper may depend on another.
Each wrapper calls next until the original method runs, then results flow back through the wrappers.

The syntax

A Chain of Command class is an ordinary class with two special features. It carries the ExtensionOf attribute naming the class it extends, and it is declared final. By convention its name ends in _Extension. Inside it, a method with the same name and parameters as the base method becomes a wrapper as soon as it calls next. For tables, the attribute uses tableStr instead of classStr, and for forms it uses formStr.

A Chain of Command wrapper on a table method. The standard validation runs first through next; the wrapper adds one rule.
[ExtensionOf(tableStr(PurchLine))]
final class PurchLineCRInspection_Extension
{
    public boolean validateWrite()
    {
        boolean ok = next validateWrite();

        if (ok && this.CRInspectionRequired && !this.CRHeatNumber)
        {
            ok = checkFailed("@CRCustom:HeatNumberRequired");
        }

        return ok;
    }
}

Prudence noticed three things in the example. First, this inside the extension refers to the PurchLine record, so the new fields from lesson 2 and the standard fields are both available. Second, the wrapper calls next unconditionally and keeps its result, then adds its own check only if the standard checks passed. Third, the message uses a label from the CRCustom label file, so the error is translated for the French Canadian and Mexican users.

The rules about next

The compiler enforces strict rules about the next call, and Microsoft documents them precisely. The wrapper must always call next, so that the original method and any other wrappers still run. The call must be a first-level statement in the method body: it cannot sit inside an if statement, inside a loop, after a return statement or inside a logical expression. From Platform update 21, the call may sit inside a try, catch or finally block, but it still may not be conditional. These rules exist because every wrapper in every model depends on the chain being complete.

Rules for the next call, as documented by Microsoft.
AllowedNot allowed
boolean ok = next validateWrite(); as a first statementif (x) { ok = next validateWrite(); }
Code before next, then next, then code afterreturn before next
next inside try, catch or finally (Platform update 21 and later)next inside a while, do-while or for loop
Changing arguments before passing them to nextnext inside a logical expression such as a && next b()

There is one documented exception. A standard method marked with the Replaceable attribute does not require an unconditional next. Microsoft adds this attribute to methods where it expects extenders to substitute their own logic in some cases, for example a method that calculates a default value. Even then, Microsoft's guidance is that an extension should skip next only under its own specific condition and call next otherwise, so other extensions still get their chance. The compiler does not enforce that guidance, which makes it a code review item.

Which methods can be wrapped

Public and protected methods of classes, tables, data entities and forms can be wrapped. Private methods cannot. A method marked final cannot be wrapped unless Microsoft has added the Wrappable(true) attribute to it, and a public or protected method marked Wrappable(false) cannot be wrapped either. The Hookable(false) attribute blocks Chain of Command as well as pre- and post-event handlers. Static methods can be wrapped, and the wrapper must also be declared static; this does not apply to forms, whose static methods have no meaning in X++.

A wrapper on a derived class can wrap a method inherited from its base class. If class B extends class A and an extension of B wraps a method defined in A, only instances of B run the wrapper; instances of A and of other subclasses do not. This is a useful way to change behaviour for one subtype of a document, such as one kind of purchase line type, without affecting all of them.

Access to the base class

From Platform update 9, an extension class can use the protected methods and member variables of the class it extends, not only from wrappers but from any method in the extension. Extensions can also add new methods and new member variables, which become part of the augmented class. The one thing an extension cannot do is extend a constructor. A method called new in an extension class defines the extension's own constructor, which must be public and take no arguments; it does not wrap the base class constructor.

Default parameter values follow a specific rule. A wrapper can wrap a method that has default parameters, but the wrapper's signature must omit the default values. If the standard method is declared with str message = "Hi", the wrapper is declared with just str message. Prudence hit this rule on her first try and the compiler error message pointed straight at it.

Wrapping nested form parts

Forms are made of nested parts: data sources, fields within data sources, and controls. Each nested part needs its own extension class with a specific attribute. A data source is extended with ExtensionOf on formDataSourceStr, naming the form and the data source; a data source field uses formDataFieldStr with the form, data source and field; a control uses formControlStr with the form and control name. Calling next in these wrappers behaves like calling super in the form, so the base runtime behaviour still happens. The original form's package does not need to be recompiled to extend its nested parts from another model.

Wrapping the active method of the PurchLine data source on the purchase order form, so the heat number can be edited only when inspection is required.
[ExtensionOf(formDataSourceStr(PurchTable, PurchLine))]
final class PurchTableFormPurchLineDS_CRInspection_Extension
{
    public int active()
    {
        int ret = next active();

        FormDataSource ds = this;
        PurchLine line = ds.cursor();
        ds.object(fieldNum(PurchLine, CRHeatNumber)).allowEdit(line.CRInspectionRequired);

        return ret;
    }
}

Microsoft's documentation adds two cautions about forms. Visual Studio's editor does not list which nested-part methods are wrappable, so developers must check the documented signatures. And X++ methods that exist only in X++ on form controls and data sources compile when wrapped but are not called at run time; only the methods the form runtime itself calls are effective wrapping points. Desmond told Prudence to set a breakpoint in every new form wrapper and prove it fires before building anything on it.

Order and independence

When several models wrap the same method, the order in which their wrappers run is not guaranteed. A Cobalt Ridge wrapper may run before or after a wrapper in an ISV model, and that order can change between builds. Every wrapper must therefore be written so that it works whatever runs before or after it. In practice this means checking the state it needs rather than assuming another extension set it, and never relying on another extension's side effects.

Wrapping data entity methods

Data entities are extended with the same technique. A wrapper on a data entity method, such as validateWrite, insertEntityDataSource or mapEntityToDataSource, uses ExtensionOf with tableStr and the entity's name, because entities are table-like elements. Prudence used one on the purchase order lines entity so that a heat number loaded from Excel or a data project went through the same rule as one typed on the form. Desmond pointed out that the PurchLine.validateWrite wrapper already covered most entity writes, because the entity writes through the table, but entity-specific wrappers are the right place for rules that only make sense for imports, such as converting a foundry's heat format.

Debugging wrappers

A wrapper that never runs is the most common Chain of Command problem. In the unified developer experience, a developer attaches the debugger to the cloud-hosted environment from Visual Studio and sets a breakpoint in the wrapper. If the breakpoint is not hit, the usual causes are that the model was not deployed after the change, that the method is not called on this path, or that the wrapper's signature does not match the base method. The call stack window is useful once a breakpoint is hit, because it shows which other wrappers ran before the current one and confirms the chain is complete. Prudence kept a short note of the paths that reached each wrapper she wrote, such as posting from the form and posting from a batch job, so she could test each one.

A code review checklist

Desmond asked reviewers to check every pull request that added a wrapper against a short list. Is the class final and named with the _Extension suffix and the CR prefix? Is next called unconditionally, and if not, is the method marked Replaceable and is the skip limited to a Cobalt Ridge condition? Does the wrapper do as little as possible, calling a class that holds the logic? Are messages labels rather than text? Is there a test that fails if the wrapper stops running? And has the author confirmed in the reference metadata that the wrapped method is on the path that matters? The checklist made reviews quick and caught most problems before they reached a sandbox.

Why not copy the method

Prudence asked one more question: if a standard method was hard to wrap, why not copy its logic into the extension and change the copy? Desmond's answer was that a copy freezes Microsoft's logic as it was on the day it was copied. When Microsoft fixes a bug in the original or adds a feature, the copy does not get the change, and the difference may not be noticed for months. A wrapper always runs the current standard logic through next. If a wrapper cannot express what is needed, the right moves are a different extension point, a design change or an extensibility request, which lesson 11 covers.

Desmond closed the session by asking Prudence to explain Chain of Command back to him in three sentences. Her answer was that a wrapper is a final extension class method with the same signature as a public or protected standard method; that it must always call next, which runs the rest of the chain and the original; and that it can add logic before and after next but cannot depend on what other wrappers do. He said that was the whole technique, and the rest was knowing which method to wrap.

Worked problem

Blocking the receipt

Product receipts are posted by a form letter class. Prudence finds that the receipt posting checks each line in a method that returns true if the line may be posted. She wants receipts for lines that need a certificate to fail unless the certificate is recorded or waived.

Show solution
  1. Read the standard method in the reference metadata and confirm it is public or protected, not final, and not marked Hookable(false).
  2. Create a final extension class with ExtensionOf naming the posting class, and a wrapper with the same signature, omitting any default values.
  3. Call next first and keep the result, so all standard checks run.
  4. If the standard result is true and the line has CRInspectionRequired set and its CRInspectionStatus is neither Received nor Waived, write an error with checkFailed and return false.
  5. Set a breakpoint, post a test receipt in the developer environment and confirm the wrapper runs and blocks the receipt.

Answer: A wrapper that calls next unconditionally, then adds one rule on the way out, blocks the receipt without changing Microsoft's code. Lesson 12 assembles it with the rest of the design.

Common mistakes

  • MistakeCalling next inside an if statement so the standard logic only sometimes runs.

    InsteadCall next unconditionally as a first-level statement; skipping it is allowed only for Replaceable methods, and then only conditionally.

  • MistakeForgetting the final keyword or the ExtensionOf attribute.

    InsteadDeclare the extension class final and give it the ExtensionOf attribute with classStr, tableStr or formStr.

  • MistakeIncluding the default value in the wrapper's signature.

    InsteadOmit default values in the wrapper even though the base method declares them.

  • MistakeRelying on another model's wrapper having run first.

    InsteadWrite every wrapper to work regardless of the order of other wrappers.

Summary and key terms

  • Chain of Command wraps public and protected methods of classes, tables, data entities and forms in a final class marked with ExtensionOf.
  • Every wrapper must call next unconditionally as a first-level statement; Replaceable methods are the documented exception.
  • Final methods need Wrappable(true) to be wrapped; Wrappable(false) and Hookable(false) block wrapping.
  • Extensions can use protected members, add methods and fields, and wrap static methods, but cannot extend constructors.
  • Nested form parts are wrapped with formDataSourceStr, formDataFieldStr and formControlStr; wrapper order between models is not guaranteed.
Chain of Command (CoC)
The technique of wrapping a standard method in an extension class and calling next to continue the chain.
next
The keyword that calls the next wrapper or the original method.
Replaceable attribute
Marks a method whose wrappers may skip next under their own condition.
Wrappable attribute
Controls whether a method can be wrapped; Wrappable(true) opens a final method.
Hookable(false)
An attribute that blocks event handlers and Chain of Command on a method.

Practice problems

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

  1. Where in a wrapper should next be called?

    Show answer

    As a first-level statement that always runs; not inside if, loops, logical expressions or after a return.

  2. Can a wrapper on class B affect instances of its base class A?

    Show answer

    No. It runs only for instances of B, even if it wraps a method defined in A.

  3. How should the wrapper declare a parameter that has a default value in the base method?

    Show answer

    Without the default value.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz