D'fflib
HOW

Layers explained

The entry point for HOW articles, describing the different (D')fflib layers, their responsibilities and interactions; and introducing the Room Booking use-case which is used across all code examples in the layer-specific articles.

(D')fflib layers

With the publication of fflib in 2014, four main layers were introduced: Domains, Selectors, Services, and the Unit of Work. With D'fflib we formalise a fifth layer: Entrypoints. Each layer has its own role, responsibilities and interactions, allowing you to separate concerns and create maintainable and scalable codebases, so everyone can easily deduce where specific logic should be placed and how it should be called.

The table below lists the layers and frameworks in D'fflib, their defined responsibilities and the link to the detailed articles on how to properly leverage and apply such layer.

LayerResponsibilitiesDocumentation
DomainSObject-specific constants, business logic, and trigger orchestration→ HOW
Entry Bridges front-end and platform automations to core layers.
Invoking, orchestrating and translating different contexts
→ HOW
SelectorSObject-specific SOQL queries. Centralised, reusable, and security-adopted→ HOW
ServiceReusable cross-SObject business operation or functionality (like integrations)→ HOW
Unit of WorkDatabase interaction ledger to simplify registration, relationships and default handling of transactions and fallbacks→ HOW

Additionally, D'fflib includes fflib-apex-mocks, a Test Data Builder Framework and a Trigger Handler Framework.

FrameworkResponsibilitiesDocumentation
Test with mocksEnables to isolate test methods to their single-responsibility. Mocking consumed layers, keep tests understandable, and much faster→ HOW
Trigger HandlersMetadata driven handlers to allow bulkified and understandable trigger logic→ HOW

Layer interactions

Simply put, all code related logic in Salesforce can be brought back to:

  • Platform initiators
    Salesforce automations that trigger internal code, like incoming APIs, user actions (e.g. Quick Action or LWC wire) and automations (Flow/Apex) either triggered by time or record.
  • Entry layer
    Connecting end-users with the backend. Orchestrating calls into the core layers, not containing any business processes, but managing the transactions and errors, and converting payloads and exceptions to initiator suited formats. Like RestResource, Batchable, Queueable and Schedulable classes, Invocable methods, Trigger Handlers, and Controllers for LWC, Aura or Visualforce.
  • Core layers (Domains, Selectors, Services and Unit of Work)
    'Passively' invoked layers which should be caller-agnostic as they're unaware of the class and context that invoked them, nor what context it runs in. Thus throwing Exceptions instead of end-user tailored messages. Any business logic is expected to be in one of these classes, and designed for re-use.

Invocation matrix

To help understand and validate the correctness of layer selection, and avoid deep-circular dependencies between layers, the architecturally and best-practice-based interactions between layers are summarised below:

Caller to calleeEntryDomainSelectorServiceUnit of Work
Entry →
Domain →
Selector →
Service →
Unit of Work →

Hover over the icons for reasoning or examples: (allowed), (with caution) and (not applicable).


Domain vs. Service ambiguity

By definition the ruling is rather simple:

  • Domains contain SObject-specific constants and logic, and house the Trigger Handlers,
  • Services contain cross-SObject business logic.

However, in practice the line blurs. Logic that touches one SObject today might touch multiple tomorrow; and Domains can become less maintainable due to the rapid growth housing both SObject business logic and trigger handlers. To support you in discussing the right layer for a specific SObject process next time, find the below suggestions:

Keep in Domain

SObject-specific constants, defaults and enums
SObject-specific initiations, validations, (small) business logic and type conversions
Trigger handler orchestration

When to consider a Service

Logic that touches, or is likely to touch, multiple SObjects
Logic that is likely to be extended in the future
Logic that is large enough to benefit from isolation, e.g. to enable future reuse/API exposure
Domain is already rather unwieldy and could benefit from decomposition

Multiple Services per object or process can be quite a robust setup. SRV_OpportunityRenewal, SRV_OpportunityMACD, and SRV_OpportunityValidation can all live alongside a lean DOM_Opportunities, where each Service owns one focused, reusable and scalable process.

(D')fflib thus doesn't enforce a binary cut. However, it gives the vocabulary for the team conversation. Two reasonable engineers on the same team can draw the line differently. It is important to agree on a convention early, document and adhere to it, and evaluate as the codebase grows. In the end, the essence of the Apex Enterprise Design Patterns is to aim for maintainable, scalable and testable codebases, and this should be kept in mind in any future ambiguous layer-design discussion.


Code examples use-case: Room booking system

Throughout the HOW articles, a Room Booking system is used as a running example. The model is intentionally simple: a Room__c represents a physical location, a Contact represents the person making the booking, and a RoomReservation__c junction object ties them together with a date range and a status field.

Every code snippet in the per-layer HOW articles is drawn from this same data model so that examples build on each other rather than introducing new context with every article. Where this model allows examples to be simple and understandable, while enabling us to showcase most of the framework's strengths, such as:

  • Allow guest-user vs. internal-user flows to leverage the same Selectors, while the invoking class distinguishes the user mode via Database Context
  • Upon reservation, the postal code is validated via a REST API,
  • the closest available room is suggested via a geolocation query
  • Junction record relationship registration via Unit of Work and Selector inclusion of relationship fields and subselects
  • Aggregate Result queries to check for existing reservations and calculate total revenue per room
  • A simple trigger to calculate the total price based on nightly rate and number of nights, or prevent Room deactivation when there are active future reservations

Except for the listed items, the content on this site is licensed under CC-BY-NC-4.0
and allows sharing, provided an appropriate credit and link to source.

On this page