//_blog

Brewtiful Beans Learns AT4DX, Part 8: Three Shifts, One Roaster

Sales and Marketing share Account, while Service owns the Case workflow. Joe has to make room for each team’s fields, queries, and rules without letting Org Common turn into a home for every app’s code.

After this post, you can:

  • Trace team-specific queries and rules through shared selectors and domains.
  • Coordinate sequence numbers when teams add rules to the same event.
  • Identify where shared fields, queries, and domain rules belong.

The Shared Logbook

Before any code, look at what the org actually looks like. Three teams, two shared SObjects, one set of classes:

sales-app            Sales fieldsets, method, criteria, actions
marketing-app        Marketing method, criteria, action
service-app          Service method, criteria, action, service impl

sales-marketing-common   Account.EngagementSegment__c
sales-service-common     Account.CustomerTier__c
org-common               AccountsSelector, AccountDomain, CasesSelector, CaseDomain

fflib · force-di · AT4DX

Read the arrows as “depends on.” Sales depends on both common packages. Marketing depends only on sales-marketing-common, and Service depends on sales-service-common for the shared Account field. Nothing depends on a sibling app. That isolation is the point: when Marketing changes its method, Service doesn’t need a redeploy.

The table on the next section is the one to bookmark.

What Lives Where

Artifact Package Why
IAccountsSelector, AccountsSelector, AccountDomain org-common The one Account selector and domain
ICasesSelector, CasesSelector, CaseDomain org-common The one Case selector and domain
Account.EngagementSegment__c sales-marketing-common Shared by Sales and Marketing
Account.CustomerTier__c sales-service-common Shared by Sales and Service
SelectLargeAccountsSelectorMethod, Sales fieldset, Sales criteria and actions sales-app Sales-owned query, fields, and rules
SelectByEngagementScoreSelectorMethod, Marketing fieldset, Marketing criteria and action marketing-app Marketing-owned query and rules
SelectOverdueCasesSelectorMethod, Service criteria and action service-app Service-owned Case query and rules

Notice what’s missing. There’s no SalesAccountsSelector, no MarketingAccountDomain, no ServiceCaseDomain. Every team’s behavior lands on a class someone else already owns, through a hook.

Typing Tax: Without AT4DX, each team writes its own Account selector, its own Account domain, and its own trigger hook. Three teams means three selectors that drift apart, three domains fighting over the same before update handler, and a bug report that starts with “which Account query is this?” The table above is the price of avoiding that, and it’s paid once.

Org Common: The Singular Owners

Everyone shares these classes, and they stay small. The selector declares the base fields every team needs, and it exposes the factory:

public interface IAccountsSelector extends IApplicationSObjectSelector {
    List<Account> selectById(Set<Id> accountIds);
}

public with sharing class AccountsSelector
    extends ApplicationSObjectSelector
    implements IAccountsSelector {

    public static IAccountsSelector newInstance() {
        return (IAccountsSelector)
            Application.Selector.newInstance(Account.SObjectType);
    }

    public Schema.SObjectType getSObjectType() {
        return Account.SObjectType;
    }

    public override List<Schema.SObjectField> getSObjectFieldList() {
        return new List<Schema.SObjectField>{
            Account.Id, Account.Name, Account.Type,
            Account.AnnualRevenue, Account.OwnerId,
            Account.BillingCountry, Account.Status__c
        };
    }

    public List<Account> selectById(Set<Id> accountIds) {
        return (List<Account>) selectSObjectsById(accountIds);
    }
}

Fieldset injection will add the Sales and Marketing fields to every query this selector builds. The selector doesn’t know those fields exist.

The domain is the one place a rule lives in code rather than metadata, and only because it’s an invariant that’s true for every team: a blank billing country defaults to the US.

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);
        }
    }

    public override void onBeforeUpdate(Map<Id, SObject> existingRecords) {
        for (Account account : (List<Account>) getRecords()) {
            if (String.isBlank(account.BillingCountry)) {
                account.BillingCountry = 'US';
            }
        }
    }
}

Keep the bar high for what goes in here. In Part 7, the team-specific rules lived in metadata. Anything that belongs to one team goes in that team’s package.

Two bindings wire it up:

ApplicationFactory_SelectorBinding__mdt   Account → AccountsSelector        (Priority 10)
ApplicationFactory_DomainBinding__mdt     Account → AccountDomain.Constructor

CasesSelector and CaseDomain follow the same shape on Case, with their own bindings.

Common queries from anywhere in the org call the factory directly:

List<Account> accounts = AccountsSelector.newInstance().selectById(accountIds);

Sales: Fields, a Query, and Rules

Sales is the busiest shift, so it touches every mechanism.

Fields

Sales owns a fieldset listing the downstream fields its queries need:

Account.SalesAccountFields: SalesStage__c, ExpectedRevenue__c, EngagementSegment__c, CustomerTier__c

SelectorConfig_FieldSetInclusion__mdt
  BindingSObject__c: Account
  FieldsetName__c:   SalesAccountFields

Every query built by AccountsSelector now includes those fields, and Org Common never names them. This is the mechanism from Part 5.

A Query

The large-account query belongs to Sales, so it’s an injectable method on the shared selector, not a method on a Sales selector:

// Package: sales-app
public inherited sharing class SelectLargeAccountsSelectorMethod
    extends AbstractSelectorMethodInjectable
    implements ISelectorMethodInjectable {

    public List<SObject> selectQuery() {
        Parameters params = (Parameters) getParameters();
        Decimal minimumRevenue = params.minimumRevenue;

        fflib_QueryFactory queryFactory = newQueryFactory();
        queryFactory.setCondition(Account.AnnualRevenue + ' >= :minimumRevenue');
        queryFactory.addOrdering(Account.AnnualRevenue, fflib_QueryFactory.SortOrder.DESCENDING);
        return Database.query(queryFactory.toSOQL());
    }

    public class Parameters implements ISelectorMethodParameterable {
        public Decimal minimumRevenue;
    }
}

Callers pass the class and its parameters:

SelectLargeAccountsSelectorMethod.Parameters params =
    new SelectLargeAccountsSelectorMethod.Parameters();
params.minimumRevenue = 1000000;

List<Account> largeAccounts = AccountsSelector.newInstance().selectInjection(
    SelectLargeAccountsSelectorMethod.class, params);

Rules

Sales’ rules are the classification from Part 7. Strategic and standard are mutually exclusive, so they get separate sequences:

Sequence 10 — Account / TriggerExecution / Before_Update
  10.10 Criteria LargeAccountCriteria
  10.20 Action   MarkStrategicAccountAction
Sequence 20 — Account / TriggerExecution / Before_Update
  20.10 Criteria SmallAccountCriteria
  20.20 Action   MarkStandardAccountAction
Sequence 30 — Account / TriggerExecution / After_Update
  30.10 Criteria LargeAccountCriteria
  30.20 Action   NotifyExternalSystemAction   (ExecuteAsynchronous__c = true)

Every line is a DomainProcessBinding__mdt record. No Sales subclass of AccountDomain exists, and no trigger code changes.

Marketing: One Query, One Rule

Marketing shares Account with Sales and injects into the same AccountsSelector and AccountDomain. It never creates a MarketingAccountsSelector.

Its query is a method injection:

// Package: marketing-app
public inherited sharing class SelectByEngagementScoreSelectorMethod
    extends AbstractSelectorMethodInjectable
    implements ISelectorMethodInjectable {

    public List<SObject> selectQuery() {
        Parameters params = (Parameters) getParameters();
        Decimal minimumScore = params.minimumScore;
        return Database.query(
            newQueryFactory()
                .setCondition(Account.EngagementScore__c + ' >= :minimumScore')
                .toSOQL());
    }

    public class Parameters implements ISelectorMethodParameterable {
        public Decimal minimumScore;
    }
}

Its rule is a criteria and an action that flags low-engagement accounts for nurture outreach:

public class LowEngagementAccountCriteria 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> matches = new List<SObject>();
        for (Account account : records) {
            if (account.EngagementScore__c == null || account.EngagementScore__c < 30) {
                matches.add(account);
            }
        }
        return matches;
    }
}

public class EnqueueNurtureSequenceAction extends DomainProcessAbstractAction {
    public override void runInProcess() {
        for (SObject record : this.records) {
            ((Account) record).NurtureStatus__c = 'Needs Outreach';
        }
    }
}
Sequence 40 — Account / TriggerExecution / Before_Update
  40.10 Criteria LowEngagementAccountCriteria
  40.20 Action   EnqueueNurtureSequenceAction

Keeping the Grounds Separate

Sequences group by the integer part of OrderOfExecution__c, within one SObject, context, and trigger operation. Sales’ Before_Update sequences are 10 and 20, and its After_Update sequence is 30. Marketing picks 40 on Before_Update, which keeps its criteria out of Sales’ chains.

The wiki’s rule is to agree on per-package OrderOfExecution__c ranges whenever more than one package injects into the same domain event. One workable split, and the one this series uses: Sales takes 10–30 on Account, Marketing takes 40–49 on Account, and Service gets its own range on Case. The numbers are a team agreement, not a framework rule, so write the agreement down.

OrderOfExecution__c is Number(4,2), so the sequence is the integer part (0 to 99), and the decimals order bindings inside it. Writing 40.10 keeps the sequence readable.

Service: Cases and Overdue Work

Service owns Case, so it injects into CasesSelector and CaseDomain. Its query finds overdue cases:

// Package: service-app
public inherited sharing class SelectOverdueCasesSelectorMethod
    extends AbstractSelectorMethodInjectable
    implements ISelectorMethodInjectable {

    public List<SObject> selectQuery() {
        Parameters params = (Parameters) getParameters();
        DateTime cutoff = DateTime.now().addHours(-params.hoursOverdue);
        return Database.query(
            newQueryFactory()
                .setCondition(Case.Status + ' != \'Closed\' AND ' + Case.CreatedDate + ' < :cutoff')
                .toSOQL());
    }

    public class Parameters implements ISelectorMethodParameterable {
        public Integer hoursOverdue;
    }
}

Its rule escalates overdue cases. The threshold is a constant, and the selector caller passes the same value as hoursOverdue, so the query and the rule can’t drift apart:

public class OverdueCaseCriteria implements IDomainProcessCriteria {
    public static final Integer OVERDUE_HOURS = 24;
    private List<Case> records;

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

    public List<SObject> run() {
        DateTime cutoff = DateTime.now().addHours(-OVERDUE_HOURS);
        List<SObject> matches = new List<SObject>();
        for (Case caseRecord : records) {
            if (caseRecord.Status != 'Closed' && caseRecord.CreatedDate < cutoff) {
                matches.add(caseRecord);
            }
        }
        return matches;
    }
}

public class EscalateToManagerAction extends DomainProcessAbstractAction {
    public override void runInProcess() {
        for (SObject record : this.records) {
            Case caseRecord = (Case) record;
            caseRecord.EscalationLevel__c = 'Manager';
            caseRecord.Priority = 'High';
        }
    }
}
Sequence 10 — Case / TriggerExecution / Before_Update
  10.10 Criteria OverdueCaseCriteria
  10.20 Action   EscalateToManagerAction

Sequence 10 is free to reuse because these bindings target Case, not Account. Sequences only group within one SObject.

The Pour-Over Flow

Here’s one Sales update, end to end:

  1. A user saves a batch of Accounts. The AccountTrigger hands them to the one AccountDomain.
  2. ApplicationSObjectDomain runs onBeforeUpdate, which defaults any blank billing country to US.
  3. The coordinator runs sequence 10. LargeAccountCriteria filters the full batch, and MarkStrategicAccountAction sets Status__c = 'Strategic' on the survivors.
  4. Sequence 20 starts from the full batch again. SmallAccountCriteria filters, and MarkStandardAccountAction sets Status__c = 'Standard'.
  5. Sequence 30 runs after the update. LargeAccountCriteria filters again, and NotifyExternalSystemAction enqueues the queueable.
  6. Marketing’s sequence 40 ran in step 1 alongside the others, with its own criteria. Nothing in its chain touched Sales’ records.

Testing the Shared Pieces

Mock the shared selector the way Part 4 taught you. Stub sObjectType() first, because setMock requires it:

IAccountsSelector selector = (IAccountsSelector) mocks.mock(IAccountsSelector.class);

mocks.startStubbing();
mocks.when(selector.sObjectType()).thenReturn(Account.SObjectType);
mocks.when(selector.selectById(accountIds)).thenReturn(expectedAccounts);
mocks.stopStubbing();

Application.Selector.setMock(Account.SObjectType, selector);

Stub injected calls on the same interface:

mocks.when(selector.selectInjection(
    SelectLargeAccountsSelectorMethod.class, params)).thenReturn(expectedAccounts);

Test each team’s criteria and actions on their own, then drive the coordinator against the org-common AccountDomain. Never test through an app-specific domain, because there isn’t one:

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

Verify that work gets staged with the AT4DX method:

((IApplicationSObjectUnitOfWork) mocks.verify(mockUow, 1)).register(expectedAccounts);

Part 9 covers the full mock cheat sheet.

The Boundaries, Summarized

  • Org Common is the single owner of AccountsSelector, AccountDomain, CasesSelector, and CaseDomain.
  • Business Common packages hold schema shared by the applications that use it.
  • Each app adds fields through fieldsets, queries through selector methods, and behavior through criteria and actions. It coordinates its OrderOfExecution__c range with the others.
  • Service owns the Case query and overdue-case behavior in service-app.
  • DML is staged through uow.register(...) and commitWork().

Check Your Brew

1. Why does Marketing’s rule use sequence 40 instead of reusing 10?

  • A. Sequence numbers must be unique across the whole org
  • B. Sequences group within one SObject, context, and operation, so picking a range that doesn’t collide with Sales’ chains keeps Marketing’s criteria from merging into them
  • C. Sequence 10 is reserved for Service
  • D. Marketing’s binding would otherwise fail to deploy
Reveal the answer

B. Criteria in the same sequence chain with AND. Marketing’s criteria would have been ANDed into Sales’ sequence, which isn’t what either team wants. Agreeing on ranges per package keeps the chains separate.

2. Where should Service put its overdue-case query?

  • A. Add it to the shared CasesSelector in Org Common
  • B. Implement it as a selector method in service-app and call it through CasesSelector
  • C. Add it to the Sales Account selector
  • D. Put the SOQL in OverdueCaseCriteria
Reveal the answer

B. The query belongs to Service, so its implementation stays in service-app. Selector method injection lets it use the shared CasesSelector without adding Service-specific query logic to Org Common.

3. Why does the org have one AccountDomain instead of a SalesAccountDomain and a MarketingAccountDomain?

  • A. Teams contribute domain rules through bindings while sharing one domain and trigger
  • B. fflib doesn’t support subclassing domains
  • C. Domains can only be used by one team at a time
  • D. Subclassed domains run twice on every save
Reveal the answer

A. One domain per SObject means one place the trigger lands. Teams add rules through metadata, so they don’t compete over trigger code or fight over the same handler.

Next up: Part 9, Tasting Notes, is about testing. We’ll look at the mock toolkit, isolated tests, and integration tests, and why the shared org doesn’t make testing harder.