//_blog

Brewtiful Beans Learns AT4DX, Part 7: Sorting the Good Beans

Marketing already has rules for Account changes. Now Sales wants to classify its accounts: above a million in annual revenue is Strategic; everything else is Standard. Joe can write both checks. The harder question is where they belong when both teams share AccountDomain.

AT4DX lets each team supply rules to the domain. A Criteria chooses which records qualify; an Action decides what to do with them. The binding determines when each piece runs.

After this post, you can:

  • Write a Criteria class and an Action class.
  • Explain why mutually exclusive rules must live in separate sequences.
  • Wire a trigger rule with DomainProcessBinding__mdt and keep AccountDomain empty.

The Account Domain

You might be used to writing Account domain logic following a pattern like this:

public override void onAfterUpdate(Map<Id, SObject> existing) {
    List<Account> largeAccounts = new List<Account>();
    for (Account acct : this.accountRecords) {
        if (acct.AnnualRevenue > 1000000) {
            largeAccounts.add(acct);
        }
    }
    if (!largeAccounts.isEmpty()) {
        for (Account a : largeAccounts) { a.Status__c = 'Strategic'; }
        // ... other additions as requirements arrive
    }
}

Every new rule means editing this class, redeploying it, and colliding with every other team whose logic runs in the same trigger.

AT4DX’s base class, ApplicationSObjectDomain, already overrides the fflib lifecycle methods (handleBeforeInsert, handleBeforeUpdate, handleAfterUpdate, and so on). Each override runs the base logic, then asks the coordinator to run any matching bindings. So your AccountDomain looks like this:

public with sharing class AccountDomain extends ApplicationSObjectDomain {
    public AccountDomain(List<SObject> records) {
        super(records);
    }

    public class Constructor implements fflib_SObjectDomain.IConstructable {
        public fflib_SObjectDomain construct(List<SObject> records) {
            return new AccountDomain(records);
        }
    }
    // No trigger overrides. The DomainProcessBinding__mdt records drive everything.
}

No onAfterUpdate override. No DomainProcessCoordinator call. New rules arrive as new Criteria, Action, and binding records, often from a different package, and this file never changes.

Typing Tax: Each rule is now a class, a binding record, and a test class. A single if statement became three artifacts. For a team that adds rules every week, that’s what keeps the domain from turning into the 800-line trigger from Part 0.

The Two Interfaces

Criteria: IDomainProcessCriteria

public interface IDomainProcessCriteria {
    IDomainProcessCriteria setRecordsToEvaluate(List<SObject> records);
    List<SObject> run();
}

A Criteria filters. It receives records, and it returns the ones that match. It doesn’t do DML, and it doesn’t call services. It’s a pure function from records to a subset.

Actions: DomainProcessAbstractAction

Actions extend an abstract base class. You implement runInProcess() and read two protected fields:

  • this.records holds the records that survived the criteria.
  • this.uow holds a Unit of Work, if one was passed in.

Sequences: Why Mutually Exclusive Rules Need Separate Lines

When the coordinator runs, it collects every active binding for the SObject, context, and operation. Then it groups them into sequences. A sequence is the integer part of OrderOfExecution__c. Bindings 10.10 and 10.20 belong to sequence 10. Bindings 20.10 and 20.20 belong to sequence 20.

Within a sequence:

  1. Criteria run first, in order, and they chain. The first criteria filters the full record set, the second filters the result, and so on. That’s a progressive AND.
  2. Actions run next, each on the final survivors.
  3. The next sequence starts over from the full record set.

Joe sees the trap when Sales tries to classify both tiers. If LargeAccountCriteria and SmallAccountCriteria sit in one sequence, the second filter only sees accounts that passed the first. No account can be both large and small, so the chain matches nothing. Put each rule in its own sequence, and each one starts again from the full record set.

OrderOfExecution__c is a Number(4,2) field. Sequences run from 0 to 99, and the two decimal places order bindings within a sequence. Use 10.10, not 100, so the sequence is easy to read.

The Criteria

Two classes split the revenue tiers. Both are pure filters:

public class LargeAccountCriteria implements IDomainProcessCriteria {
    private List<Account> records;

    public IDomainProcessCriteria setRecordsToEvaluate(List<SObject> records) {
        this.records = (List<Account>) records;
        return this;
    }

    public List<SObject> run() {
        List<SObject> matched = new List<SObject>();
        for (Account acct : records) {
            if (acct.AnnualRevenue != null && acct.AnnualRevenue > 1000000) {
                matched.add(acct);
            }
        }
        return matched;
    }
}
public class SmallAccountCriteria implements IDomainProcessCriteria {
    private List<Account> records;

    public IDomainProcessCriteria setRecordsToEvaluate(List<SObject> records) {
        this.records = (List<Account>) records;
        return this;
    }

    public List<SObject> run() {
        List<SObject> matched = new List<SObject>();
        for (Account acct : records) {
            if (acct.AnnualRevenue == null || acct.AnnualRevenue <= 1000000) {
                matched.add(acct);
            }
        }
        return matched;
    }
}

Notice that SmallAccountCriteria treats a null revenue as small. That’s a business decision, and it’s written where you can see it.

The Synchronous Actions

These run in before-update context. They set Status__c on the records in place, and no Unit of Work is needed:

public class MarkStrategicAccountAction extends DomainProcessAbstractAction {
    public override void runInProcess() {
        for (SObject record : this.records) {
            ((Account) record).Status__c = 'Strategic';
        }
    }
}

public class MarkStandardAccountAction extends DomainProcessAbstractAction {
    public override void runInProcess() {
        for (SObject record : this.records) {
            ((Account) record).Status__c = 'Standard';
        }
    }
}

The Asynchronous Action

Notifying an external system means a callout, and callouts belong in a queueable. The action hands off the work:

public class NotifyExternalSystemAction extends DomainProcessAbstractAction {
    public override void runInProcess() {
        List<Account> strategicAccounts = (List<Account>) this.records;
        System.enqueueJob(new AccountNotificationQueueable(strategicAccounts));
    }
}

public class AccountNotificationQueueable implements Queueable, Database.AllowsCallouts {
    private List<Account> accounts;

    public AccountNotificationQueueable(List<Account> accounts) {
        this.accounts = accounts;
    }

    public void execute(QueueableContext ctx) {
        // Call the external REST API, publish a platform event, etc.
    }
}

The action enqueues a callout-capable job. If its binding also sets ExecuteAsynchronous__c = true, the coordinator first runs the action asynchronously, and the action then enqueues the separate callout job. That is a two-step queueable handoff; use it when the action itself needs to run outside the trigger transaction. The notification belongs in an after-update sequence.

The Bindings

The bindings are the wiring. Here’s the Brewtiful layout:

Sequence Operation Criteria (order) Action (order)
10 Before_Update LargeAccountCriteria (10.10) MarkStrategicAccountAction (10.20)
20 Before_Update SmallAccountCriteria (20.10) MarkStandardAccountAction (20.20)
30 After_Update LargeAccountCriteria (30.10) NotifyExternalSystemAction (30.20, async)

Each binding is a DomainProcessBinding__mdt record. The key fields are:

  • Type__c: Criteria or Action
  • ClassToInject__c: the class name
  • RelatedDomainBindingSObject__c: Account
  • ProcessContext__c: TriggerExecution
  • TriggerOperation__c: Before_Update or After_Update
  • OrderOfExecution__c: the sequence and order
  • ExecuteAsynchronous__c: true to queue the Action itself
  • IsActive__c: true to run, false to disable the rule without a deploy

Here’s one of them as the source-tracked XML:

<?xml version="1.0" encoding="UTF-8"?>
<CustomMetadata xmlns="http://soap.sforce.com/2006/04/metadata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <label>Large Account Criteria</label>
    <values><field>Type__c</field><value xsi:type="xsd:string">Criteria</value></values>
    <values><field>ClassToInject__c</field><value xsi:type="xsd:string">LargeAccountCriteria</value></values>
    <values><field>RelatedDomainBindingSObject__c</field><value xsi:type="xsd:string">Account</value></values>
    <values><field>ProcessContext__c</field><value xsi:type="xsd:string">TriggerExecution</value></values>
    <values><field>TriggerOperation__c</field><value xsi:type="xsd:string">Before_Update</value></values>
    <values><field>OrderOfExecution__c</field><value xsi:type="xsd:double">10.10</value></values>
    <values><field>IsActive__c</field><value xsi:type="xsd:boolean">true</value></values>
</CustomMetadata>

Accounts that are inserted need the same classification, so deploy a parallel set of bindings with Before_Insert as well. The domain doesn’t change for either one.

The Order of Operations

For one Account update, the flow is:

  1. The AccountTrigger hands the records to AccountDomain.
  2. Before-update: the coordinator runs sequence 10. LargeAccountCriteria filters all records, and MarkStrategicAccountAction sets Status__c = 'Strategic' on the survivors.
  3. Before-update: sequence 20 starts from the full set again. SmallAccountCriteria filters, and MarkStandardAccountAction sets Status__c = 'Standard'.
  4. After-update: sequence 30 runs. LargeAccountCriteria filters again, and NotifyExternalSystemAction enqueues the queueable for the large accounts.

Criteria always run before Actions within a sequence. Each sequence re-filters, so sequences don’t affect one another.

Testing in Isolation

Each class is small, so each one gets a small test.

Criteria need no database and no metadata:

@IsTest
static void largeAccountCriteria_returnsOnlyLargeAccounts() {
    List<SObject> testAccounts = new List<SObject>{
        new Account(Name = 'SmallCo', AnnualRevenue = 500000),
        new Account(Name = 'BigCo',   AnnualRevenue = 2000000),
        new Account(Name = 'MidCo',   AnnualRevenue = 1000000),
        new Account(Name = 'HugeCo',  AnnualRevenue = 5000000)
    };

    LargeAccountCriteria criteria = new LargeAccountCriteria();
    criteria.setRecordsToEvaluate(testAccounts);
    List<SObject> result = criteria.run();

    System.assertEquals(2, result.size(),
        'Only BigCo and HugeCo have AnnualRevenue > 1M');
}

Actions get driven the way the coordinator drives them. Give the action records with setRecordsToActOn, run it, and read the result:

@IsTest
static void markStrategicAction_setsStatusField() {
    List<SObject> accounts = new List<SObject>{
        new Account(Id = fflib_IDGenerator.generate(Account.SObjectType),
                    Name = 'BigCo', AnnualRevenue = 2000000)
    };

    MarkStrategicAccountAction action = new MarkStrategicAccountAction();
    action.setRecordsToActOn(accounts);
    action.runInProcess();

    System.assertEquals('Strategic', ((Account) accounts[0]).Status__c);
}

The whole pipeline can run without reading metadata. setMockDomainProcessBindings supplies the bindings directly. Match the operation to the binding you’re testing, so this test uses Before_Update:

@IsTest
static void coordinator_classifiesLargeAccountsAsStrategic() {
    DomainProcessCoordinator.setMockDomainProcessBindings(
        new List<DomainProcessBinding__mdt>{
            new DomainProcessBinding__mdt(
                Type__c = 'Criteria',
                ClassToInject__c = 'LargeAccountCriteria',
                RelatedDomainBindingSObject__c = 'Account',
                ProcessContext__c = 'TriggerExecution',
                TriggerOperation__c = 'Before_Update',
                OrderOfExecution__c = 10.10,
                IsActive__c = true),
            new DomainProcessBinding__mdt(
                Type__c = 'Action',
                ClassToInject__c = 'MarkStrategicAccountAction',
                RelatedDomainBindingSObject__c = 'Account',
                ProcessContext__c = 'TriggerExecution',
                TriggerOperation__c = 'Before_Update',
                OrderOfExecution__c = 10.20,
                IsActive__c = true)
        });

    List<Account> accounts = new List<Account>{
        new Account(Name = 'BigCo',   AnnualRevenue = 2000000),
        new Account(Name = 'SmallCo', AnnualRevenue = 100000)
    };

    AccountDomain domain = new AccountDomain(accounts);
    new DomainProcessCoordinator(domain).processDomainLogicInjections(
        DomainProcessConstants.PROCESS_CONTEXT.TriggerExecution,
        System.TriggerOperation.Before_Update);

    System.assertEquals('Strategic', accounts[0].Status__c);
    System.assertEquals(null,        accounts[1].Status__c);
}

If an action needs to stage DML against other records, inject a mocked Unit of Work with action.setUnitOfWork(mockUow), then verify the register(...) calls.

Running Rules Outside a Trigger

Sometimes you want the same machinery in a domain method you call yourself, such as a monthly recalculation. That’s the DomainMethodExecution context. Instead of a trigger operation, the bindings carry a token:

public void recalculateRevenueTiers(IApplicationSObjectUnitOfWork uow) {
    getDomainProcessCoordinator().processDomainLogicInjections(
        'AccountRevenueTierRecalc', uow);
}

The matching bindings set ProcessContext__c = DomainMethodExecution and DomainMethodToken__c = AccountRevenueTierRecalc, and leave TriggerOperation__c blank. Because a Unit of Work is passed in, the actions can stage DML through this.uow.

Check Your Brew

1. Why are LargeAccountCriteria and SmallAccountCriteria in separate sequences?

  • A. Apex doesn’t allow two criteria classes in one trigger
  • B. The OrderOfExecution__c field can only hold one value per SObject
  • C. Criteria in the same sequence run in parallel and conflict
  • D. Each sequence re-filters the full record set, so putting mutually exclusive rules together would AND them and match nothing
Reveal the answer

D. Criteria in one sequence chain with AND. A record can’t be both large and small, so the chain would be empty. Separate sequences each start from the full set.

2. Why does MarkStrategicAccountAction belong in a before-update binding rather than after-update?

  • A. Field changes made in a before trigger save with the record; in an after trigger they’re lost without DML
  • B. Actions can’t run after a trigger fires
  • C. Before-update is faster
  • D. The Status__c field is read-only after update
Reveal the answer

A. In-place mutations persist only in before-trigger context, where the platform saves the record’s current values. In an after trigger, the action would need a Unit of Work and DML to save its changes.

3. What makes the notification action run asynchronously?

  • A. Its class extends Queueable
  • B. It’s declared @future
  • C. ExecuteAsynchronous__c = true on its binding, with the action enqueuing a queueable
  • D. It’s in a sequence above 50
Reveal the answer

C. The binding flag tells the coordinator to hand the action off asynchronously. The action class enqueues the queueable that does the callout.

Next up: Part 8, Three Shifts, One Roaster, brings Sales, Marketing, and Service into the same org. Joe’s shared selectors and domains are about to get busy.