Platform
Apex Enterprise Patterns with fflib: Selector, Unit of Work, and tests without DML
When Apex grows past a few trigger handlers, the pain is always the same: SOQL scattered everywhere, DML in an order nobody controls, and service tests that are slow because they all touch the database. The fflib enterprise patterns fix each one. A practitioner walk through the Selector, Domain, Unit of Work and Service layers, with the code, and which parts to adopt first.
The tell is a service test that takes four seconds to run. It inserts an Account, a Contact, two Opportunities and a pricebook entry to assert one line of logic, and it does that because the code under test runs its own SOQL and DML inline. Multiply by three hundred tests and your deploy spends its life in RunLocalTests.
The fflib enterprise patterns exist to break that coupling. They are Martin Fowler’s enterprise application patterns adapted to Apex by Andrew Fawcett. They buy you three specific things: a Selector so your SOQL lives in one class per object, a Unit of Work so one call commits all your DML in the right order, and layers thin enough to mock so a service test runs without touching the database.
My advice up front, because the framework is often adopted all-or-nothing and should not be: take the Unit of Work and the Selector first. They pay for themselves on any org. Add the full Domain layer and the mocking only when the org’s size and team count justify the ceremony. Adopt fflib because you feel the pain it removes, not because it is respected.
The Selector: all the SOQL for one object, in one place
A Selector class owns every query for an SObject. Instead of [SELECT ...] scattered across triggers, controllers and services, you have one class that knows which fields to pull and how to build each query.
public inherited sharing class OpportunitiesSelector extends fflib_SObjectSelector {
public Schema.SObjectType getSObjectType() {
return Opportunity.SObjectType;
}
public List<Schema.SObjectField> getSObjectFieldList() {
return new List<Schema.SObjectField> {
Opportunity.Id, Opportunity.Name, Opportunity.StageName,
Opportunity.Amount, Opportunity.CloseDate, Opportunity.AccountId
};
}
public List<Opportunity> selectById(Set<Id> ids) {
return (List<Opportunity>) selectSObjectsById(ids);
}
public List<Opportunity> selectOpenByAccountId(Set<Id> accountIds) {
return (List<Opportunity>) Database.query(
newQueryFactory()
.setCondition('AccountId IN :accountIds AND IsClosed = false')
.toSOQL());
}
}
Two things happen here that matter beyond tidiness. The field list is declared once, so a new field needed by three features is added in one place instead of three. And newQueryFactory() builds the SELECT from that field list, so you stop hand-maintaining column lists in string SOQL, which is where a non-selective query creeps in.
The Selector is also the natural home for the enforcement the security review checks. Since the December 2022 release, the base class takes a data-access mode rather than the old enforceCRUD and enforceFLS flags. A selector can now run in user mode and honour the running user’s field-level security, without you writing WITH USER_MODE on every query. The Apex security scanner flags the CRUD and FLS gaps a selector is meant to close, if you want a sense of what that enforcement protects against.
The Unit of Work: one commit, in dependency order
Adopt this pattern first, because it fixes the bug that is hardest to see coming. When a process creates an Account, then Contacts that reference it, then Opportunities that reference both, the DML has to happen in that order, and the children need the parent’s Id before it exists.
The usual answer is a chain of insert statements with manual re-parenting in between. It is fragile, and it burns DML statements against the governor limits.
A Unit of Work lets you register all the work and commit it once.
fflib_ISObjectUnitOfWork uow = Application.UnitOfWork.newInstance();
Account acct = new Account(Name = 'Northwind');
uow.registerNew(acct);
Contact primary = new Contact(LastName = 'Pugh');
uow.registerNew(primary, Contact.AccountId, acct); // child, FK field, parent
Opportunity opp = new Opportunity(
Name = 'Northwind renewal', StageName = 'Prospecting', CloseDate = Date.today().addMonths(2));
uow.registerNew(opp, Opportunity.AccountId, acct);
uow.commitWork();
You never wrote an Id. The Unit of Work resolves the relationships, inserts the parent first, stamps the foreign keys, then inserts the children. The whole thing runs inside one transaction that rolls back as a unit if anything fails. registerDirty and registerDeleted do the same for updates and deletes, and everything commits in the order the factory declared its SObject types.
That last point is the configuration you have to get right, and it lives in the Application factory below.
The Application factory: the seam that makes everything mockable
The Application class is a small registry that hands out instances of the other layers. It looks like boilerplate. The file is the single most important one in the framework, because it is the seam where a test swaps a real layer for a mock.
public class Application {
public static final fflib_Application.UnitOfWorkFactory UnitOfWork =
new fflib_Application.UnitOfWorkFactory(
new List<SObjectType> {
Account.SObjectType, Contact.SObjectType, Opportunity.SObjectType, Task.SObjectType
});
public static final fflib_Application.ServiceFactory Service =
new fflib_Application.ServiceFactory(
new Map<Type, Type> { IOpportunityService.class => OpportunityServiceImpl.class });
public static final fflib_Application.SelectorFactory Selector =
new fflib_Application.SelectorFactory(
new Map<SObjectType, Type> { Opportunity.SObjectType => OpportunitiesSelector.class });
}
The list passed to the Unit of Work factory is the commit order. Parents before children, always. Get it wrong and commitWork throws on a foreign key, which is a loud failure and easy to fix, unlike the silent kind.
Code asks the factory for instances rather than using new:
fflib_ISObjectUnitOfWork uow = Application.UnitOfWork.newInstance();
OpportunitiesSelector oppSelector =
(OpportunitiesSelector) Application.Selector.newInstance(Opportunity.SObjectType);
Because the instance came from the factory, a test can tell the factory to return a mock instead. That one indirection is what turns an untestable service into a testable one.
The Service layer: coarse operations that orchestrate the rest
The Service layer is where a business operation lives: “close these opportunities as won and schedule onboarding.” The layer is coarse-grained on purpose, one public method per operation, and it orchestrates selectors, domains and the Unit of Work rather than doing SOQL and DML itself.
The convention is a static facade, an interface, and an implementation. The facade keeps call sites clean; the interface is what the factory maps to an implementation.
public with sharing class OpportunityService {
public static void closeWon(Set<Id> opportunityIds) {
service().closeWon(opportunityIds);
}
private static IOpportunityService service() {
return (IOpportunityService) Application.Service.newInstance(IOpportunityService.class);
}
}
public with sharing class OpportunityServiceImpl implements IOpportunityService {
public void closeWon(Set<Id> opportunityIds) {
fflib_ISObjectUnitOfWork uow = Application.UnitOfWork.newInstance();
OpportunitiesSelector selector =
(OpportunitiesSelector) Application.Selector.newInstance(Opportunity.SObjectType);
for (Opportunity opp : selector.selectById(opportunityIds)) {
opp.StageName = 'Closed Won';
uow.registerDirty(opp);
uow.registerNew(new Task(
Subject = 'Kick off onboarding',
WhatId = opp.Id,
ActivityDate = Date.today().addDays(2)));
}
uow.commitWork();
}
}
Notice what the implementation does not contain: no inline SOQL, no update, no insert. It asks the Selector for records and registers its intentions with the Unit of Work. That one move is the whole trick, and it makes the next part possible.
The test that touches nothing
Here is the payoff. Because the service got its Selector and Unit of Work from the factory, the test replaces both with mocks from fflib-apex-mocks, asserts the service registered the right work, and never runs a query or a DML statement.
@IsTest
private class OpportunityServiceTest {
@IsTest
static void closeWonSetsStageAndSchedulesTask() {
fflib_ApexMocks mocks = new fflib_ApexMocks();
fflib_ISObjectUnitOfWork uowMock =
(fflib_ISObjectUnitOfWork) mocks.mock(fflib_ISObjectUnitOfWork.class);
OpportunitiesSelector selectorMock =
(OpportunitiesSelector) mocks.mock(OpportunitiesSelector.class);
Id oppId = fflib_IDGenerator.generate(Opportunity.SObjectType);
mocks.startStubbing();
mocks.when(selectorMock.sObjectType()).thenReturn(Opportunity.SObjectType);
mocks.when(selectorMock.selectById(new Set<Id>{ oppId }))
.thenReturn(new List<Opportunity>{
new Opportunity(Id = oppId, StageName = 'Proposal')
});
mocks.stopStubbing();
Application.UnitOfWork.setMock(uowMock);
Application.Selector.setMock(selectorMock);
Test.startTest();
OpportunityService.closeWon(new Set<Id>{ oppId });
Test.stopTest();
((fflib_ISObjectUnitOfWork) mocks.verify(uowMock)).registerDirty(
fflib_Match.sObjectWith(new Map<SObjectField, Object>{
Opportunity.StageName => 'Closed Won'
}));
((fflib_ISObjectUnitOfWork) mocks.verify(uowMock)).registerNew(
(SObject) fflib_Match.anySObject());
((fflib_ISObjectUnitOfWork) mocks.verify(uowMock, 1)).commitWork();
}
}
No records were inserted. fflib_IDGenerator.generate produces a valid-looking Id without a database, the Selector mock returns the Opportunity the test wants, and mocks.verify asserts the service set the stage to Closed Won, registered a new Task, and committed once. The test runs in milliseconds and fails only when the logic changes, not when an unrelated validation rule or required field three objects away changes.
The Apex test best practices point at the same discipline from the other direction. Tests that touch the database are testing the database as much as your code. A mock-based service test isolates the behaviour you wrote. You still need integration tests that run the real DML, and the platform’s own integration test framework is where those belong now, but you need far fewer of them.
The Domain layer, and when to skip it
The fourth layer is the Domain, which holds the behaviour and validation for records of a type: defaults, validation, and the trigger logic for that object.
public inherited sharing class Opportunities extends fflib_SObjectDomain {
public Opportunities(List<Opportunity> records) {
super(records);
}
public override void onValidate() {
for (Opportunity opp : (List<Opportunity>) Records) {
if (opp.Amount == null || opp.Amount <= 0) {
opp.Amount.addError('Amount must be greater than zero');
}
}
}
public class Constructor implements fflib_SObjectDomain.IConstructable {
public fflib_SObjectDomain construct(List<SObject> records) {
return new Opportunities((List<Opportunity>) records);
}
}
}
The Domain is the layer I tell teams to add last. On a large org with many developers writing to the same objects, putting validation and trigger logic behind a Domain class is worth the ceremony, and it pairs naturally with a trigger framework that dispatches to it. On a five-object build with one developer, the Domain layer is structure you will not use, and the Selector plus Unit of Work already removed most of the pain. Separation of concerns is a tool, not a virtue in itself.
What it costs
The framework is two code dependencies you deploy and keep current: fflib-apex-common and fflib-apex-mocks, with the mocks library deployed first. Both are a real supply-chain decision, and someone on the team has to own upgrades.
The ceremony is real too. A trivial one-object feature is more files under fflib than without it. The patterns earn their keep when logic is shared across features, when more than one person writes to the same objects, and when test time has become a tax on every deploy. They are overhead on a small, stable org that rarely changes, which is why this is a judgement call and not a mandate. The technical-debt math is the same as any architecture decision: pay structure now to make change cheap later, but only where change is coming.
Understanding the basics
What is fflib in Salesforce?
fflib is the common name for the Apex Enterprise Patterns, a set of open-source libraries (fflib-apex-common and fflib-apex-mocks) that apply Martin Fowler’s enterprise application patterns to Apex. They give you Selector, Domain, Unit of Work and Service layers, plus a mocking framework for unit tests, and are widely used in AppExchange managed packages.
What does the Unit of Work pattern do?
It lets you register new, changed and deleted records and their relationships, then commit them all in one call. It resolves parent-child foreign keys automatically, inserts records in dependency order, wraps the work in a single transaction, and minimises the number of DML statements against the governor limits.
Why use a Selector class instead of inline SOQL?
A Selector keeps every query for an SObject in one class with a single field list, so queries are consistent, a new field is added once, and security enforcement lives in one place. It also makes the query layer mockable, so services that use it can be unit-tested without hitting the database.
Do I need the whole fflib framework?
No. The Unit of Work and Selector pay off on almost any org and are the place to start. The full Domain layer and extensive mocking are worth the ceremony on large, multi-developer orgs, and are overhead on a small, stable one. Adopt the parts that remove pain you feel.
Start with the two that pay immediately
If you take one thing from this, make it the Unit of Work. It removes a class of relationship-ordering bugs on the first process you convert, and it costs almost nothing to understand. The Selector is the second, because it is where your SOQL stops leaking into every layer and where user-mode security gets a home.
The Domain layer, the mocking, the full factory wiring: add those when the org grows into them. A framework adopted ahead of the pain it solves is just more code to test. Adopted at the right time, it is the difference between an org that is expensive to change and one that is not.
If your Apex has grown past the point where a change is safe to make, a consulting engagement can introduce these patterns incrementally without a rewrite, or run the org health scorecard first to see where the untested, tightly-coupled code is.