Brewtiful Beans Learns AT4DX, Part 0: Patterns 101
Brewtiful Beans is a growing wholesale coffee roaster. It sells beans to cafés, runs marketing campaigns, and handles support tickets, all in one Salesforce org. Three teams share that org. This series follows them as they learn to stop colliding with a framework that keeps them out of each other’s way: AT4DX.
AT4DX is built on patterns from fflib and is part of a collection of open source libraries called Apex Enterprise Patterns. We’ll start with an intro to fflib as a primer. If you’ve written Apex for a while, most of it will look familiar. If fflib is new to you, this is the on-ramp. Let’s get grounded.
After this post, you can:
- Say in one sentence what a Selector, Domain, Service, and Unit of Work each do.
- Spot the smell from putting all your business logic in a single trigger.
- Read a basic
AccountsSelector.selectById()and an fflib trigger handler.
One Trigger to Rule Them All
Joe is Brewtiful’s barista-turned-admin. Last year he inherited the org’s AccountTrigger, which had grown to about 800 lines. It queries related records, makes business decisions, and saves the results, all in one place.
Picture a café where one barista takes the order, grinds the beans, pulls the shot, bags the coffee, and does the books, all at the same counter. At 8 a.m. it works. By lunch, nobody can change anything without spilling something.
Here’s a stripped-down version of the same shape. The field and the rule are made up for the example:
trigger AccountTrigger on Account (after update) {
// Query: fetch related deals
List<Opportunity> deals = [
SELECT Id, StageName FROM Opportunity
WHERE AccountId IN :Trigger.newMap.keySet()
];
// Decide: a business rule buried in the trigger
for (Opportunity deal : deals) {
if (deal.StageName == 'Closed Won') {
deal.Ship_Priority__c = 'Roast Now';
}
}
// Save: DML with no ordering and no seam for tests
update deals;
}
The trigger does three jobs at once, and each one has a cost:
- The SOQL can’t be reused. The next team that needs “deals for these accounts” writes the query again, and the copies drift apart.
- The rule can’t be tested alone. To check it, you have to fire the trigger, which means DML and test data for every case.
- The DML is scattered. If another part of the same transaction also updates Opportunities, you end up with two
updatestatements and no control over their order.
Four Roles in the Roastery
fflib splits that one counter into four roles:
| Role | Owns | Café job |
|---|---|---|
| Selector | SOQL for one SObject | Finds the beans |
| Domain | Business rules for records of one SObject | The recipe |
| Service | One use case, start to finish | The shift manager |
| Unit of Work | Batching DML and committing it in dependency order | The order rail |
Each role gets one job, and the trigger stops making decisions.
Selector: Finds the Beans
A selector is the only place SOQL for an SObject lives. Here’s a minimal fflib selector:
public inherited sharing class AccountsSelector extends fflib_SObjectSelector {
public Schema.SObjectType getSObjectType() {
return Account.SObjectType;
}
public List<Schema.SObjectField> getSObjectFieldList() {
return new List<Schema.SObjectField>{
Account.Id,
Account.Name,
Account.AnnualRevenue
};
}
public List<Account> selectById(Set<Id> accountIds) {
return (List<Account>) selectSObjectsById(accountIds);
}
}
getSObjectFieldList() declares the fields every query returns. selectById reuses the base class to build and run the query. Nothing else in the codebase should write SELECT ... FROM Account.
Domain: The Recipe
A domain wraps a list of records of one SObject and holds the rules for them. fflib_SObjectDomain also handles the trigger plumbing, so the trigger body shrinks to one line:
trigger AccountTrigger on Account (
before insert, before update, after insert, after update
) {
fflib_SObjectDomain.triggerHandler(AccountDomain.class);
}
The rules now live in the domain class. The trigger routes records to it and decides nothing itself.
Service: The Shift Manager
A service runs one use case. It asks selectors for records, applies domain logic, and commits changes through a Unit of Work. Services don’t contain SOQL and don’t write DML directly.
public with sharing class AccountService {
public static void retireSlogans(Set<Id> accountIds) {
fflib_SObjectUnitOfWork uow = new fflib_SObjectUnitOfWork(
new List<SObjectType>{ Account.SObjectType }
);
for (Account acct : new AccountsSelector().selectById(accountIds)) {
acct.Slogan__c = null;
uow.registerDirty(acct);
}
uow.commitWork();
}
}
Notice that the service calls new AccountsSelector() directly. That’s fine for now. Part 2 looks at why it becomes a problem.
Unit of Work: The Order Rail
A Unit of Work collects changes and performs them at the end, in an order you declare. registerDirty queues an update, registerNew queues an insert, and commitWork() runs them all. List your SObject types in dependency order (Accounts before Contacts) and parents are saved before their children.
Why Separate the Beans?
Three reasons, roughly in the order they bite:
- Testability. A selector can be swapped out in a test, and a domain can run on in-memory records. You don’t need the trigger to fire to check a rule.
- Reuse. Once
selectByIdexists, every service shares the same query. There’s one place to fix it. - Predictable DML. A Unit of Work batches changes, so you’re less likely to hit DML limits by accident, and the commit order is explicit.
Check your brew
1. Which layer should own the SOQL for an SObject?
- A. The trigger body
- B. The selector
- C. The Unit of Work
- D. The service
Reveal the answer
B. The selector owns SOQL for its SObject, so each query lives in one reusable place. Services call the selector. They don’t write SOQL themselves.
2. What problem does the Unit of Work solve?
- A. It enforces field-level security
- B. It replaces the trigger framework
- C. It batches DML and commits it in a declared, dependency-safe order
- D. It caches query results between transactions
Reveal the answer
C. You register changes, then call commitWork() once. The Unit of Work runs the DML in the order you declared the SObject types.
3. Why shouldn’t business logic live directly in the trigger body?
- A. Apex doesn’t allow
ifstatements in triggers - B. Triggers run in a separate org
- C. A trigger can only run one DML statement
- D. Logic in the trigger is hard to reuse and test on its own, and other code paths can’t call it
Reveal the answer
D. Logic inside the trigger can only run when the trigger fires. Moving it into a domain or service makes it reusable and testable without firing the trigger.
Next up: Part 1, One Selector, Three Teams, where we see how several apps share Org Common’s selector and add their own needs through injection. Keep these four roles in mind. AT4DX builds on them.