D'fflib
HOWLayers

Entrypoints

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

Characteristics

An Entrypoint is the front door of your Apex code: the class the platform calls when a user clicks a button in a Lightning Web Component, a Flow runs an action, or a scheduled job starts. It receives the request, validates input, hands the work to the layer that knows what to do, and translates the outcome - success or failure - back into something the caller understands. Think of a receptionist: he/she doesn't make the decisions, but makes sure the request reaches the right desk and the answer comes back in a usable form.

Responsibilities

As translation layer between external callers (LWC, Flow, Visualforce, Batch, Schedulable, Queueable) and the D'fflib core layers, methods typically follow a similar structure:

Input validation (mostly for user-input-triggered entrypoints).
Transaction management and ownership.
Delegation to core layers for SObjectType or business-specific logic (Domains, Selectors and Services).
Exception handling and Log registration.
Caller-appropriate response conversion.

Interactions

InteractionLayers
Invoked byPlatform and external callers: LWC, Flow, Visualforce, Scheduler, Database.executeBatch(), System.enqueueJob(). Never by other Apex classes
CallingSelectors, Domains, Services, Unit of Work

Entry point types

Entry Point TypeAnnotation / InterfaceClass prefix
Agent & Flow actions@InvocableMethodFlow_
Aura & LWC methods@AuraEnabledCTRL_
BatchDatabase.BatchableBatch_
QueueableQueueableQueue_
ScheduledSchedulableSched_
Visualforce(standard public class)CTRL_

Incoming APIs (@RestResource) follow Service naming (SRVi_) despite being a system entry.

Rules

  • Methods are caller specific. Thus responses should be caller-friendly, e.g. user-friendly failure message in users' language.
  • Entrypoints are never called from other Apex classes, only by the platform.
  • Entrypoints orchestrate, implying all business logic should be delegated to Domains and/or Services.
  • Methods should be bulkified and accept a Set<Id>, List<Id> or List<SObject> as input to be scalable and reusable.
  • Reusable functionalities should ideally be centralised in a corresponding service, domain or utility.
  • Entrypoints are responsible for Transaction and Exception management, thus initiating and committing Unit of Work.

Initiation

How to call

Entrypoints are invoked by the platform, not by Apex code. There is no newInstance(). The platform resolves and invokes the annotated method directly: LWC JavaScript calls @AuraEnabled methods via import (imperative) or @wire (only for cacheable = true); Flows call @InvocableMethod actions; Visualforce binds to a controller class and platform calls Batch, Queueable and Schedulable execute() methods when triggered by a schedule or process.

Class boilerplate

Since there is no instantiation, nor inherited methods, there is no framework (boilerplate) code needed to properly construct an Entrypoint class. Each type could be suggested a skeleton per method for consistency (like shown in examples below), but this remains a project decision to embrace.


Examples

Below you find code examples per type of Entrypoint. Examples are simplified, though some snippets can be found in full in the code-examples repository (see optional GitHub icon top-right of snippet block).

Front-end controllers (Aura, LWC, Visualforce)

These classes act as the interface between the front-end and the backend business logic. They handle input validation, delegate processing to the appropriate services or domains, and format the response for the front-end.

Class organisation While for Visualforce and Aura one controller is tightly coupled to the page, for LWC there is more flexibility to separate concerns. Implying for LWC you theoretically could call a Domain method for an SObject specific method directly. However, this would conflict with the caller-agnostic behaviour of a Domain and therefore it is always recommended to wrap such Domain interaction within a Controller class.

Additionally, it's good to be conscious of permissions, as a user should be granted access to an Apex class (by permission set or profile) to be able to call an AuraEnabled method. This could influence the decision to scatter or centralise the controller methods.

Class skeleton All controllers are expected to follow the same skeleton (validate, delegate, respond), although LWC and Aura require a static @AuraEnabled method, whereas Visualforce leverages public properties and action methods.

Example The class CTRL_RoomReservations exposes three methods:

Each method validates its input, delegates to the appropriate service or domain and returns a standardised SRV_Response.Response so the front-end developers can consistently handle responses. For this, one errorResponse helper is set up to centralise exception translation.

CTRL_RoomReservations.cls
public with sharing class CTRL_RoomReservations{
    // Data retrieval: validate -> selector -> respond
    @AuraEnabled( cacheable = false )
    public static SRV_Response.Response getAvailableRooms( Date checkIn, Date checkOut ){
        try{
            // Input validation
            dfflib_Utils.verifyNotNull( checkIn, 'checkIn date' );
            dfflib_Utils.verifyNotNull( checkOut, 'checkOut date' );
            if( checkOut <= checkIn ){
                throw new dfflib_Utils.InvalidInputValueException( DOM_RoomReservations.MSG_INVALID_DATE_RANGE );
            }

            // Delegate to Selector, enforcing full user-configured security
            List<Room__c> rooms = SEL_Rooms.newInstance( dfflib_Database.Context.FULL )
                .selectAvailableByDateRange( checkIn, checkOut );

            // Convert results to Response
            return SRV_Response.newInstance()
                .setResponse( SRV_Response.TYPES.OK, null )
                .setPayload( rooms )
                .getResponse();
        } catch( Exception ex ){
            return errorResponse( ex );
        }
    }
}
CTRL_RoomReservations.cls
public with sharing class CTRL_RoomReservations{
    // Data-insertion: validate -> UoW -> register -> commit -> respond
    @AuraEnabled
    public static SRV_Response.Response createReservations( List<RoomReservation__c> reservations ){
        try{
            // Input validation
            dfflib_Utils.verifyNotEmpty( reservations, 'reservations' );
            DOM_RoomReservations.newInstance( reservations ).validateRecords();

            // Delegate to Unit of Work, enforcing full security and enabling SaveResults due to allOrNone = false
            dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL );
            uow.registerNewAllOrNone( RoomReservation__c.SObjectType, false );
            uow.registerNew( reservations );
            uow.commitWork();

            // Loop SaveResults to collect any errors for partial success feedback
            Map<Integer, String> errors = new Map<Integer, String>();
            // ... logic to process results, see the SaveResults section of the Unit of Work article

            // Pass success or error message(s) to front-end
            if( errors.isEmpty() ){
                return SRV_Response.newInstance()
                    .setResponse( SRV_Response.TYPES.CREATED, null )
                    .getResponse();
            } else{
                return SRV_Response.newInstance()
                    .setResponse( SRV_Response.TYPES.DML_ERROR, errors.size() + ' of ' + reservations.size() + ' reservations failed' )
                    .setPayload( errors )
                    .getResponse();
            }
        } catch( Exception ex ){
            return errorResponse( ex );
        }
    }
}
CTRL_RoomReservations.cls
public with sharing class CTRL_RoomReservations{
    // Data-changing method: validate -> UoW -> register -> commit -> respond
    @AuraEnabled
    public static SRV_Response.Response cancelReservations( List<Id> reservationIds ){
        try{
            // Input validation
            dfflib_Utils.verifyNotEmpty( reservationIds, 'reservationIds' );

            // FULL Context applies UserMode, so no extra record-access check is needed
            dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL );
            for( Integer i = 0, j = reservationIds.size(); i < j; i++ ){
                uow.registerDirty(
                    new RoomReservation__c( Id = reservationIds[ i ], Status__c = DOM_RoomReservations.STATUS_CANCELLED )
                );
            }
            uow.commitWork();

            // Errors are processed in the catch-block
            return SRV_Response.newInstance()
                .setResponse( SRV_Response.TYPES.OK, null )
                .getResponse();
        } catch( Exception ex ){
            return errorResponse( ex );
        }
    }
}
CTRL_RoomReservations.cls
public with sharing class CTRL_RoomReservations{
    // User-friendly messages instead of technical exception details
    public static final String MSG_DML_ERROR        = 'Something went wrong during the database interaction, contact support if the issue persists.';
    public static final String MSG_PROCESSING_ERROR = 'Something went wrong during the operation, contact support if the issue persists.';

    // Maps a caught Exception to a user-friendly SRV_Response, setting Response type by Exception type
    private static SRV_Response.Response errorResponse( Exception ex ){
        SRV_Response.TYPES responseType;
        String message = ex.getMessage();
        if( ex instanceof dfflib_Utils.InvalidInputValueException ){
            responseType = SRV_Response.TYPES.INVALID_REQUEST;     // validation message is already user-friendly
        } else if( ex instanceof DmlException ){
            responseType = SRV_Response.TYPES.DML_ERROR;
            message = MSG_DML_ERROR;
        } else{
            responseType = SRV_Response.TYPES.PROCESSING_ERROR;
            message = MSG_PROCESSING_ERROR;
        }

        // ... log the exception to allow tracking and debugging
        return SRV_Response.newInstance()
            .setResponse( responseType, message )
            .getResponse();
    }
}

Be aware

  • Position the Entrypoint methods as true orchestrators, making them easy to read and maintain.
  • Methods must be public static and the class is recommended to default to with sharing
  • cacheable = true is required for @wire but forbids DML and caches results client-side. Use cacheable = false (as above) when data may change between requests, and for anything that writes.
  • Status values and messages come from Domains or Services, never hardcoded in the Entrypoint.
  • @AuraEnabled methods can't accept Set<Id>; use List<Id> for bulk Id input.
  • Parameters are deserialised from the client: use primitives, Id, SObject lists or @AuraEnabled-annotated wrapper classes. Always validate, as the client is untrusted.
  • Aura and LWC need the Apex class to be accessible to the user (Permission Set / Profile class access); Visualforce needs it on the page's controller access list.

In above examples a uniform SRV_Response.Response (type, message and payload) is returned (for LWC, SRV_Response.LWC_Response extends it with isSuccess), with a standard type (OK, CREATED, INVALID_REQUEST, DML_ERROR, PROCESSING_ERROR, ...) so the front-end can easily act upon this. This makes front-end more maintainable and easier to understand, but also - mostly for larger projects - allows you to decouple front-end and backend development.

From security perspective, for public front-end components, it's good to consider wrapping data. This avoids exposing the underlying object or field API names to possible malicious users. Such inner class would perfectly fit in the Entrypoint, including the conversion from retrieved data to it.

Ensure to specify @AuraEnabled on the variables, as otherwise they won't be properly serialised nor accessible for Aura and LWC components.

Example of front-end Comparable AppointmentWrapper
public class AppointmentWrapper implements Comparable{
    @AuraEnabled public ServiceAppointment record;
    @AuraEnabled public Date appointmentDate;

    public AppointmentWrapper( ServiceAppointment rec ){
        this.record = rec;
        this.appointmentDate = rec.SchedStartTime?.date();
    }

    public Integer compareTo( Object compareInput ){
        AppointmentWrapper otherWrapper = ( AppointmentWrapper ) compareInput;

        // If for same date, compare the start time
        if( this.appointmentDate == otherWrapper.appointmentDate ){
            if( this.record.SchedStartTime < otherWrapper.record.SchedStartTime ){
                return -1;
            } else if( this.record.SchedStartTime > otherWrapper.record.SchedStartTime ){
                return 1;
            } else{
                return 0;
            }
        } else if( this.appointmentDate == null ){
            return 1;
        } else if( otherWrapper.appointmentDate == null ){
            return -1;
        // Else, if appointment dates are different and not null, sort per logical order
        } else {
            if( this.appointmentDate < otherWrapper.appointmentDate ){
                return -1;
            } else{
                return 1;
            }
        }
    }
}

Agents and Flows

Autolaunched flows, screenflows and Agents (Agentforce Actions) can invoke Apex via @InvocableMethod. They can define custom wrappers with @InvocableVariable, and can receive a single List of request wrapper objects (e.g. List<Request>) to ensure a bulkified approach. This implies that if your autolaunched flow is invoked from a trigger with 10 records, this will initiate 10 record-triggered-flows, but the invocable method will be invoked only once with a list of 10 request objects, ensuring bulk processing.

Bulkified input In below example, for the sake of simplicity, we ignore the risks of performing an action within a loop due to the non-bulkified API. If you'd have such API that does need to move to Production:

  • For screenflows, one can assume only one record per invocation, thus allowing requests[ 0 ].
  • For autolaunched flows, it's recommended to introduce a bulk-api-service which will wrap itself around the individual calls, cautiously controlling and owning the transactions with unit of work, etc. Separating the concerns of Flow and Service and allowing reusability of that API.

Class skeleton Comparable to Controller classes, the skeleton for Invocable Methods is to validate, delegate, and handle responses. However, the validation also includes extracting values from the List-input to allow constructing the List of SObjects/Strings/Ids to invoke other layers, such as a singular query.

Flow_AddressLookup.cls
public with sharing class Flow_AddressLookup{
    public class Request{
        @InvocableVariable( required = true label = 'Postal Code' description = 'Dutch postal code (e.g. 1234AB)' )
        public String postalCode;

        // ... houseNumber
    }

    public class Response{
        @InvocableVariable( label = 'Address Found' )
        public Boolean addressFound;

        @InvocableVariable( label = 'Street' )
        public String street;        

        @InvocableVariable( label = 'Error Message' )
        public String errorMessage;

        // ... city, municipality, province
    }

    @InvocableMethod( 
        label = 'Look Up Address by Postal Code'
        description = 'Retrieves address details for a Dutch postal code and house number'
        callout = true
    )
    public static List<Response> lookupAddresses( List<Request> requests ){
        // Construct List of Response objects corresponding to same sequence as received requests
        List<Response> responses = new List<Response>();

        // In real code: either fetch only first record for screen-flow, or bulkify calling layers to avoid action within loop
        for( Integer i = 0, j = requests.size(); i < j; i++ ){
            Request req = requests[ i ];
            Response resp = new Response();
            try{
                // Delegate to the Service
                SRVo_PostalCodeValidation.AddressResult result = SRVo_PostalCodeValidation.newInstance().lookupAddress( req.postalCode, req.houseNumber );

                // ... business logic: assigning results to Response (addressFound, street, city)
            } catch( Exception ex ){
                // Capture the error on the row, do not fail the entire interview
                resp.addressFound = false;
                resp.errorMessage = ex.getMessage();
            }
            responses.add( resp );
        }

        return responses;
    }
}

Be aware

  • @InvocableMethod is static, one per class, and takes at most one List parameter. The sequence of input and output-List should always correspond.
  • Wrapper classes must be public (or global) and fields need @InvocableVariable to be visible to the Flow.
  • label and description are what admins see; write those for them, not for developers. The descriptions will be used by AI Agents to decide when the action is applicable.
  • Set callout = true when the Service performs a callout, so Flow builders can avoid performing DMLs before and after causing failures at runtime.
  • Exceptions should be properly caught and converted to List<Response>, to avoid an uncaught Exception triggering the Flow fault path for the full record set.
  • Always be careful to avoid actions (DML, queries, callouts) within loops, as this can lead to governor limit issues and non-bulkified behaviour.

Asynchronous (Batch, Queueable, Schedulable)

Asynchronous Salesforce entrypoint classes (queued or batch) own transaction management and are independent of caller context. Processing and logging must be self-contained, as there is no initiating class to return to. Schedulable entrypoints should only dispatch the jobs and not hold any domain logic or perform DMLs.

public with sharing class Batch_ConfirmPendingReservations implements Database.Batchable<SObject>{
    // start() - delegate to Selector for query scope
    public Database.QueryLocator start( Database.BatchableContext bc ){
        return SEL_RoomReservations.newInstance( dfflib_Database.Context.FULL )
            .getQueryLocatorForPendingReservations();
    }

    // execute() - delegate to layers, while owning transaction management with a UoW per chunk
    public void execute( Database.BatchableContext bc, List<RoomReservation__c> scope ){
        dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL );
        try{
            DOM_RoomReservations.newInstance( scope ).confirmReservations( uow );
            uow.commitWork();
        } catch( Exception ex ){
            // ... log failure; do not re-throw (would abort the chunk with unhandled exception)
        }
    }

    // finish() - wrap-up Batch after all chunks are processed, logging and possibly triggering next iteration
    public void finish( Database.BatchableContext bc ){
        // ... log completion, chain next job if needed
    }
}
public with sharing class Queue_ConfirmReservations implements Queueable {
    private Set<Id> recordIds;   // Pass Ids, not SObjects: data may be stale by the time it runs

    public Queue_ConfirmReservations( Set<Id> recordIds ){
        this.recordIds = recordIds;
    }

    public void execute( QueueableContext ctx ){
        try{
            dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL );
            // ... business logic: re-query via Selector, call Domain / Service
            // e.g. DOM_RoomReservations.newInstance( recordIds ).confirmReservations( uow );
            uow.commitWork();
        } catch( Exception ex ){
            // ... log failure; do not re-throw (would abort the job without feedback)
        } finally{
            // ... validate whether next Queueable in chain should be initiated
        }
    }
}
Sched_ConfirmReservations.cls (illustrative)
public with sharing class Sched_ConfirmReservations implements Schedulable {
    public void execute( SchedulableContext ctx ){
        // Dispatch only, preferably fetching Batch-size from metadata type
        Database.executeBatch( new Batch_ConfirmPendingReservations(), 200 );
    }
}

Above code snippets are illustrative and not part of the code-examples.

Be aware

  • Like Invocable Apex, all Exceptions should be properly handled and logged, to avoid silent or breaking failures and to allow the process to be rerun.
  • To reduce the number of classes, a Scheduled Batch could live in one class. Implementing both interfaces (implements Database.Batchable<sObject>, Schedulable) and defining both execute-functions.
  • Use Database.Stateful only when state must survive between chunks; it increases serialisation cost.
  • It is not possible to share one Unit of Work across multiple Batch chunks, since UoW can't be serialised and therefore can't be shared as a stateful variable.
  • Batch scope size (executeBatch( job, size )) determines the transaction size; lower it for heavy Domains or callouts.
  • Callouts in Batch / Queueable require Database.AllowsCallouts.
  • Queueable and Schedulable constructors must serialise: pass Ids and simple values, not SObjects with relationships or non-serialisable types.
  • Async jobs run as the user who scheduled or enqueued them; keep with sharing and pass dfflib_Database.Context.FULL (as above) so that user's security applies, or specify a more lenient Context (e.g. NONE, skipping CRUD/FLS and sharing) only where the job must act beyond that user's access.

@future methods

We've consciously left @future annotated methods out of above section. Despite them sharing the asynchronous entrypoint role with Batch or Queueable, there are a couple nuances why we wouldn't classify them as a type and thus with its own class (prefix).

  • Any method can be annotated with @future to run asynchronously. Like a Domain method, dedicated to one specific SObjectType.
  • Future methods have their restrictions, which is why we would recommend Queueable in most cases. (e.g. parameter limitation to (Collections) of primitives, no ability to monitor, or chain/sequentially call to split a payload into smaller parts)

Hence, we generally recommend using Queueable over @future methods, but when preferring it, we'd suggest to place it in the layer where the method-content would fit the best (often Domain or Service).


Testing an Entrypoint

See the Testing & Mocking article for full details on setting up mocks, stubs, and ApexMocks patterns used across all layers.

Comparable to other layers, test methods for Entrypoints should focus on validating the single-responsibility of the method at hand. This implies verifying the other layers are indeed invoked, with the relevant input-parameters passed correctly. However, the effective behaviour of such Domain or Service, should be tested in the unit test of that layer itself.

One complexity for testing Entrypoints is fluent services like SRV_Response. Mocking that class would cause each method to return null by default and thus cause a null-pointer upon the next chained method-call. In below example, a small stubResponseService() helper is set up to ensure proper return-definitions to allow successful fluent execution.

CTRL_RoomReservationsTest and Flow_AddressLookupTest cover all happy and unhappy flows, each thoroughly focusing on the responsibilities of the tested method only.

CTRL_RoomReservationsTest.cls
@IsTest
private static void createReservations_validRecords(){
    // create mocks
    fflib_ApexMocks mocks = new fflib_ApexMocks();
    dfflib_ISObjectUnitOfWork uowMock = dfflib.unitOfWork.defineMock( mocks );
    DOM_RoomReservations m_domReservations = ( DOM_RoomReservations ) dfflib.domain.defineMock( mocks, DOM_RoomReservations.class, RoomReservation__c.SObjectType );
    SRV_Response m_srvResponse = ( SRV_Response ) dfflib.service.defineMock( mocks, SRV_Response.class );

    // Given
    RoomReservation__c reservation = ( RoomReservation__c ) TestFactory.aRoomReservation()
        .asDefault()
        .mock();
    List<RoomReservation__c> reservations = new List<RoomReservation__c>{ reservation };

    // set mocks
    mocks.startStubbing();
    stubResponseService( mocks, m_srvResponse );
    mocks.stopStubbing();

    // When - mocked domain passes validation; mocked UoW returns null for getNewResults -> success path
    CTRL_RoomReservations.createReservations( reservations );

    // Then - verify records validated, UoW registered and committed, and SRV_Response received CREATED
    ( ( DOM_RoomReservations ) mocks.verify( m_domReservations, 1 ) ).validateRecords();
    ( ( dfflib_ISObjectUnitOfWork ) mocks.verify( uowMock, 1 ) ).registerNew( reservations );
    ( ( dfflib_ISObjectUnitOfWork ) mocks.verify( uowMock, 1 ) ).commitWork();
    ( ( SRV_Response ) mocks.verify( m_srvResponse, 1 ) ).setResponse( SRV_Response.TYPES.CREATED, null );
}
CTRL_RoomReservationsTest.cls
@IsTest
private static void createReservations_dmlException(){
    // create mocks
    fflib_ApexMocks mocks = new fflib_ApexMocks();
    dfflib_ISObjectUnitOfWork uowMock = dfflib.unitOfWork.defineMock( mocks );
    dfflib.domain.defineMock( mocks, DOM_RoomReservations.class, RoomReservation__c.SObjectType );
    SRV_Response m_srvResponse = ( SRV_Response ) dfflib.service.defineMock( mocks, SRV_Response.class );

    // Given - a DmlException and default RoomReservation
    String exceptionMessage = 'Fake exception message';
    RoomReservation__c reservation = ( RoomReservation__c ) TestFactory.aRoomReservation()
        .asDefault()
        .mock();

    // set mocks
    mocks.startStubbing();
    ( ( dfflib_ISObjectUnitOfWork ) mocks.doThrowWhen( new DmlException( exceptionMessage ), uowMock ) ).commitWork();
    stubResponseService( mocks, m_srvResponse );
    mocks.stopStubbing();

    // When - exception is caught -> DML_ERROR response returned instead of re-thrown
    CTRL_RoomReservations.createReservations( new List<RoomReservation__c>{ reservation } );

    // Then
    ( ( SRV_Response ) mocks.verify( m_srvResponse, 1 ) ).setResponse(
        SRV_Response.TYPES.DML_ERROR,
        exceptionMessage
    );
}
CTRL_RoomReservationsTest.cls
@IsTest
private static void createReservations_partialFailure(){
    // create mocks
    fflib_ApexMocks mocks = new fflib_ApexMocks();
    dfflib_ISObjectUnitOfWork uowMock = dfflib.unitOfWork.defineMock( mocks );
    dfflib.domain.defineMock( mocks, DOM_RoomReservations.class, RoomReservation__c.SObjectType );
    SRV_Response m_srvResponse = ( SRV_Response ) dfflib.service.defineMock( mocks, SRV_Response.class );

    // Given - two reservations, of which the second fails on insert (allOrNone = false)
    List<RoomReservation__c> reservations = new List<RoomReservation__c>{
        ( RoomReservation__c ) TestFactory.aRoomReservation().asDefault().mock(),
        ( RoomReservation__c ) TestFactory.aRoomReservation().asDefault().mock()
    };
    String dmlMessage = 'The room is already booked for these dates';
    List<Database.SaveResult> saveResults = new List<Database.SaveResult>{
        dfflib_UT_Utils.createSaveResult( fflib_IDGenerator.generate( RoomReservation__c.SObjectType ), true, null ),
        dfflib_UT_Utils.createSaveResult( null, false, dmlMessage )
    };

    // set mocks
    mocks.startStubbing();
    mocks.when( uowMock.getNewResults( RoomReservation__c.SObjectType ) ).thenReturn( saveResults );
    stubResponseService( mocks, m_srvResponse );
    mocks.stopStubbing();

    // When
    CTRL_RoomReservations.createReservations( reservations );

    // Then - committed once; DML_ERROR with the failed record's message keyed by its index
    ( ( dfflib_ISObjectUnitOfWork ) mocks.verify( uowMock, 1 ) ).commitWork();
    ( ( SRV_Response ) mocks.verify( m_srvResponse, 1 ) ).setResponse(
        SRV_Response.TYPES.DML_ERROR,
        '1 of 2 reservations failed'
    );
    ( ( SRV_Response ) mocks.verify( m_srvResponse, 1 ) ).setPayload(
        new Map<Integer, String>{ 1 => dmlMessage }
    );
}
CTRL_RoomReservationsTest.cls
/**
 * Stubs the SRV_Response mock to avoid null-pointers in the fluent chain. 
 * Must be called between startStubbing() and stopStubbing().
 */
private static void stubResponseService( fflib_ApexMocks mocks, SRV_Response m_srvResponse ){
    mocks.when( m_srvResponse.setResponse( ( SRV_Response.TYPES ) fflib_Match.anyObject(), ( String ) fflib_Match.anyObject() ) ).thenReturn( m_srvResponse );
    mocks.when( m_srvResponse.setResponse( ( SRV_Response.TYPES ) fflib_Match.anyObject(), ( String ) fflib_Match.isNull() ) ).thenReturn( m_srvResponse );
    mocks.when( m_srvResponse.setPayload( fflib_Match.anyObject() ) ).thenReturn( m_srvResponse );
    mocks.when( m_srvResponse.getResponse() ).thenReturn( null );
}

Migration steps

Since Entrypoints don't inherit any functionality, there are no mandatory changes to adopt D'fflib. Only the suggested class naming and structure ("validate, delegate and respond") could be interesting to apply, like the SRV_Response or input-validation utilities (in dfflib_Utils). This is not mandatory.


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