D'fflib
HOWLayers

Domains

Step-by-step guide on how to set up and interact with a Domain, maximise the functions and benefits, while being aware of edge cases and D'fflib specific functionalities.

Trigger Handler documentation

This article has the single responsibility to elaborate on the Domain layer, initiation and usage.
→ Click here to visit the trigger handlers documentation, to learn how those can be registered and implemented.

Characteristics

A Domain is the one place that centralises and knows the constants, validations, rules and business logic for one SObject. It's like your subject matter expert for that SObject, your central point of expertise.

Responsibilities

A Domain class has four distinct responsibilities:

Centralise all constants/statics for one object, like picklist values (TYPE_SINGLE or STATUS_CLOSED).
Perform operations on a provided fixed set of records for the SObject.
Centralise SObject specific business logic, like record validation, update or initiation (markAsCancelled()).
Host the SObject specific trigger handlers.

Interactions

InteractionLayers
Called byEntrypoints, Services, Trigger
CallingSelectors, Unit of Work

Rules

  • Methods should have a clear single responsibility and be limited to one SObjectType.
  • Methods should be caller agnostic, thus not assume any context of the caller, e.g. throw Exceptions instead of emitting user-facing messages.
  • Methods should be bulkified to be scalable and reusable.
  • Statics are prefixed by type/category for easier findability (auto-complete) and maintenance.
  • Unit of Work shouldn't be initiated nor committed, as the caller owns the transaction.
  • Generally no Services are called. This could be an indication to elevate the logic to a Service instead.
  • Generally Domains run with sharing, given the users running business processes. However, due to agnostic nature inherited sharing might fit better.

Note, the above excludes trigger handlers, which have their own context and rules, as can be found here.


Initiation

How to call

Domains are always instantiated via the (class-specific) static newInstance() factory method. Depending on project-guidelines and requirements, the newInstance() method may accept a list of records, a set of Ids, or no input at all:

// Default: List of records, which is set as scope for the Domain
DOM_RoomReservations domainByList = DOM_RoomReservations.newInstance( reservations );

// From Set of Ids. Requires the Selector for this SObjectType to exist, as fflib will perform the query internally
DOM_RoomReservations domainByIds = DOM_RoomReservations.newInstance( reservationIds );

// Empty instance, when no scope is needed for this transaction
DOM_RoomReservations domainEmpty = DOM_RoomReservations.newInstance();

Given the return value of newInstance(), the desired method can be chained easily:

CTRL_RoomReservations.cls
DOM_RoomReservations.newInstance( reservations ).validateRecords();

Class boilerplate

A Domain class extends the framework base class dfflib_SObjectDomain and typically contains its constants, a constructor that registers the trigger handlers , the static factory methods and a Constructor inner class the framework uses to instantiate it.

DOM_RoomReservations.cls
public with sharing class DOM_RoomReservations extends dfflib_SObjectDomain{
    // Statics ...

    // Constructor accepting list of records
    public DOM_RoomReservations( List<RoomReservation__c> sObjectList ){
        super( sObjectList, dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL ) );
        // Register handlers
    }

    // Business methods and trigger handler inner classes ...

    // Static newInstance methods to centralise caller construction
    // Optionally, newInstance( Set<Id> ); can be added, but be aware of the query performed internally
    public static DOM_RoomReservations newInstance(){ return newInstance( new List<RoomReservation__c>() ); }
    public static DOM_RoomReservations newInstance( List<RoomReservation__c> sObjectList ){
        return ( DOM_RoomReservations ) dfflib.domain.newInstance( sObjectList );
    }    

    // Constructor class, optionally implementing IConstructable or IConstructable2
    public class Constructor implements dfflib_SObjectDomain.IConstructable{
        public dfflib_SObjectDomain construct( List<SObject> sObjectList ){
            return new DOM_RoomReservations( ( List<RoomReservation__c> ) sObjectList );
        }
    }
}
  • dfflib_SObjectDomain extends fflib_SObjects, which in turn extends fflib_Objects. Therefore, every Domain inherits a set of generic collection utilities, as listed in Accelerators & Utilities.
  • There is no framework need to construct an interface like IDomain. Examples including such, predate the Apex Stub API to enable mocking.
  • When providing an empty-list, ensure it is typed (List<RoomReservation__c>, instead of List<SObject>), since the framework uses it to determine the SObjectType.

The framework factory (dfflib.domain) will:

  1. Check whether a mock-instance was set and return if available
  2. Retrieve the related Dfflib_Domain_Config__mdt metadata
  3. Instantiate the Domain Constructor class with the retrieved configuration and pass the records into .construct().
  4. Call the Domain constructor-method to call the dfflib_SObjectDomain constructor with the provided records and configuration.
  5. Return the constructed Domain class-instance.

It allows state to be provided when the domain is created. A setter could imply that this state can be changed later, or that the object can be used without it. Since Apex lacks Java-style reflection, this design was the best alternative without requiring a default constructor and a separate setRecords method.

Theoretically, it is possible to call dfflib.domain.newInstance() directly to avoid the static newInstance() boilerplate in your Domain. However, you'll need to cast its generic dfflib_SObjectDomain result that the Domain class would otherwise define centrally.

Regardless of choice, the recommendation is to be consistent throughout your codebase.

( ( DOM_RoomReservations ) dfflib.domain.newInstance( reservations ) ).validateRecords();

Metadata registration

Register the Domain in Dfflib_Domain_Config__mdt so the framework can resolve it via dfflib.domain.newInstance() and the trigger handler.

FieldPurposeExample
MasterLabelLabel of the mdt record. Shown in SetupRoom Reservation
DeveloperNameUnique API name of the record. Doesn't allow duplicate (___) thus write custom SObjectTypes as _cRoomReservation_c
SObjectType__cAPI name of the SObjectRoomReservation__c
Implementation_Type__cConstructor inner class pathDOM_RoomReservations.Constructor
Is_Trigger_Disabled__cIntended to switch off all trigger handling for this SObject (not yet effective)false

Code examples

Constants

All SObject-specific hardcoded strings belong in the Domain as public static final constants. This makes it easy to validate whether the static already exists (somewhere in the codebase), and encourages to leverage constants instead of hardcoded text (which simplifies possible value modifications).

To simplify future maintenance, it's recommended to group the statics, alphabetically or in sequence of process, by type/category set as prefix.

DOM_Rooms.cls
// Room Types
public static final String TYPE_CONFERENCE  = 'Conference';
public static final String TYPE_DOUBLE      = 'Double';
public static final String TYPE_SINGLE      = 'Single';
public static final String TYPE_SUITE       = 'Suite';

Methods

Typical business methods include initiation, validation, calculation, and other SObject-specific logic that is likely to be reused across the application. Below example demonstrates a typical validation method, throwing an Exception upon failure, so the caller can handle it appropriately. It leverages getRecords() to access the SObject records set in the instantiation.

DOM_RoomReservations.cls
// DOM_RoomReservations.newInstance( records ).validateRecords();
public void validateRecords(){
    List<RoomReservation__c> reservations = ( List<RoomReservation__c> ) getRecords();
    for( Integer i = 0, j = reservations.size(); i < j; i++ ){
        RoomReservation__c res = reservations[ i ];
        dfflib_Utils.verifyNotNull( res.Room__c, 'Room' );
        dfflib_Utils.verifyNotNull( res.Contact__c, 'Contact' );
        dfflib_Utils.verifyNotNull( res.CheckInDate__c, 'Check-in date' );
        dfflib_Utils.verifyNotNull( res.CheckOutDate__c, 'Check-out date' );
        if( res.CheckOutDate__c <= res.CheckInDate__c ){
            throw new dfflib_Utils.InvalidInputValueException( MSG_INVALID_DATE_RANGE );
        }
        if( res.NumberOfGuests__c == null || res.NumberOfGuests__c < 1 ){
            throw new dfflib_Utils.InvalidInputValueException( MSG_INVALID_NUMBER_OF_GUESTS );
        }
    }
}

Typically, you might want to validate all records and throw the aggregate validation errors. To keep the code simple, the above example already throws on first failure.

Other Domain method names could be initiateReservation(), calculateTotals(), applyDiscounts() and validateStatusTransition().

Inherited collection utilities

Instead of hand-written loops, business methods can leverage the utilities inherited from fflib_SObjects. Most of them are protected, so they are available inside your Domain methods.

NeedInherited utility
Collect Ids, or Ids of a parentgetRecordIds(), getParentIdFieldValues( 'Room__r.Location__c' ), getIdFieldValues( field [, includeNulls] )
Collect other field valuesgetFieldValues( field ), getStringFieldValues( field )
Narrow the scope on field valuesgetRecordsByFieldValue( field, value ), getRecordsByFieldValues( field, values )
Find (in)complete recordsgetRecordsWithBlankFieldValues( fields ), getRecordsWithAllBlankFieldValues( fields ), getRecordsWithNotBlankFieldValues( fields ), getRecordsWithAllNotBlankFieldValues( fields )
Group records per keygroupRecordsByFieldValue( field )
Bulk update or reset fieldssetFieldValue( field, value ), setFieldValueByMap( fieldToCheck, fieldToUpdate, values ), clearField( field ), clearFields( fields )
// Ids of the booked rooms, excluding nulls, e.g. to pass to SEL_Rooms
public Set<Id> getRoomIds(){
    return getIdFieldValues( RoomReservation__c.Room__c, false );
}

// Records of the scope that are still open
public List<RoomReservation__c> getOpenReservations(){
    return ( List<RoomReservation__c> ) getRecordsByFieldValues( RoomReservation__c.Status__c, new Set<Object>( STATUSES_OPEN ) );
}

// Reservations per Contact, e.g. for reporting or notifications
public Map<Object, List<SObject>> getReservationsByContact(){
    return groupRecordsByFieldValue( RoomReservation__c.Contact__c );
}

// Bulk state change on the full scope
public void markAsCancelled(){
    setFieldValue( RoomReservation__c.Status__c, STATUS_CANCELLED );
}

See the full list, including parameters and behaviour, in Accelerators & Utilities.


Testing a Domain

See Testing & Mocking for the full testing patterns.
Testing trigger handlers, including the runHandler() shortcut, is covered in Triggers & Handlers.

Like Services, Domains aren't much different in testing, compared to regular Apex classes. The only difference is in usage of inherited in-memory records and optionally domain-specific builders for test data setup. In our guidelines, we prefer positioning our Test Data Builder Framework in the respective Domain test class, but that is project-specific.

DOM_RoomReservationsTest.cls
@IsTest
private static void validateRecords_missingRoom(){
    // Given - reservation without a Room
    RoomReservation__c res = ( RoomReservation__c ) TestFactory.aRoomReservation()
        .asDefault()
        .forContact( TestFactory.aContact().asDefault() )
        .mockWithIds();

    // When / Then - validation fails on the missing Room
    try{
        DOM_RoomReservations.newInstance( new List<RoomReservation__c>{ res } ).validateRecords();
        System.Assert.fail( 'Expected dfflib_Utils.InvalidInputValueException to be thrown' );
    } catch( Exception ex ){
        System.Assert.areEqual( 'dfflib_Utils.InvalidInputValueException', ex.getTypeName(), 'Unexpected exception type' );
        System.Assert.areEqual( 'Room cannot be null', ex.getMessage(), 'Unexpected validation message' );
    }
}

Migration steps

For existing code to leverage D'fflib features, a couple migration steps are required. Below steps apply once D'fflib extensions are installed (Getting Started).

Required changes

  1. Ensure Dfflib_Domain_Config__mdt record exists
  2. Change extends fflib_SObjectDomain to extends dfflib_SObjectDomain
  3. Change [Application].domain.newInstance() to dfflib.domain.newInstance()
public with sharing class DOM_Rooms extends dfflib_SObjectDomain{
    public static DOM_Rooms newInstance( List<Room__c> sObjectList ){
        return ( DOM_Rooms ) dfflib.domain.newInstance( sObjectList );
    }
}
public with sharing class DOM_Rooms extends fflib_SObjectDomain{
    public static DOM_Rooms newInstance( List<Room__c> sObjectList ){
        return ( DOM_Rooms ) Application.domain.newInstance( sObjectList );
    }
}

Optional changes

  1. Move hooks to trigger handlers
    Register handlers in the Domain constructor and gradually move on* hook logic into them. See the Trigger Handlers migration guide. To enable the Handler Framework, the super( SObjectList ) in the Domain constructor should be extended to initiate and pass a Unit of Work, with specific dfflib_Database.Context. This defines the Context for all Trigger Handler DML operations, and instructs the Domain to enable the Handler Framework, like enableTriggerState(), which improves performance by keeping the Domain instance consistent across Trigger Events.

    public DOM_Rooms( List<Room__c> sObjectList ){
        // Initialize the domain
        super( sObjectList, dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL ) );
    
        // ... Handler registration
    }
  2. Use the inherited collection utilities
    Replace hand-written loops that collect Ids, group records or set field values with the inherited methods listed in Inherited collection utilities.


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