D'fflib
HOWLayers

Services

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

Characteristics

A Service holds the business logic that doesn't fit a single SObject: processes spanning multiple SObjects, reusable logic, and integrations in or out. It does the work, without knowing who started it. Think of it as a Specialist for one process, which owns that single-responsibility end-to-end.

Responsibilities

Services have a wide variety of responsibilities of which main are:

Coordinate logic that spans multiple SObjects, or is likely to, in the near future (e.g. invoice generation or lead conversion).
Centralise agnostic (business) logic to allow reuse (data cleansing, email service).
Integrations, both incoming and outgoing.

Split heavy processes into modular classes, respecting separation of concerns and maintainability.

Relates to Domain-Service ambiguity (→ Overview page). Multiple Services per process are valid, like SRV_OpportunityRenewal and SRV_OpportunityMACD living side by side with a lean DOM_Opportunities.

Interactions

InteractionLayers
Called byAPI, Entrypoints, Batch execute(), other Services (with caution)
CallingSelectors, Domains, Services, Unit of Work

Technically, a Service can be both the caller (e.g. for an incoming integration) and the callee. Due to this dual role, this is the only layer that, with caution, may call other instances of its own layer. The precaution is to avoid circular dependencies and unintended side effects from multiple Service instances interacting in complex ways.

Depending on the role, Services only register the relevant records to a received input-Unit of Work without committing (e.g. outgoing integration), however, for incoming integrations it is expected to initiate and control the Unit of Work internally. Similar to other layers, it remains important for Services to be caller-agnostic and never assume the context in which they are invoked.

Rules

  • Methods should have a clear single responsibility.
  • Methods should be robust and satisfy the open-close principle.
  • 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 and accept a Set<Id> or List<SObject> as input to be scalable and reusable.
  • Generally Services run with sharing, given the users running business processes. However, due to agnostic nature inherited sharing might fit better.

When being called:

  • The Service only registers and doesn't commit (even no Log records), e.g. to avoid 'uncommitted work pending' errors for integrations.

Initiation

How to call

Comparable to other layers, Services are instantiated via newInstance(), enabling mocking.

Entrypoint or Batch — calling a Service
// Entrypoint owns the UoW construction and the commit
dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance();
SRV_RoomReservations.newInstance().confirmReservation( reservationIds, uow );
uow.commitWork();

The framework factory (dfflib.service) will:

  1. Check whether a mock-instance was set and return if available
  2. Retrieve the related Dfflib_Service_Config__mdt metadata
  3. Instantiate the Service class with the retrieved configuration.
  4. Return the constructed Service class-instance.

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

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

SRV_RoomReservations serviceDirect = ( SRV_RoomReservations ) dfflib.service.newInstance( SRV_RoomReservations.class );

Class boilerplate

Unlike the other layers, the Service class requires only a static newInstance() method to function. Which is even obsolete for an incoming API Service class, as this class is not expected to be instantiated nor referenced within your own codebase.

public with sharing class SRV_RoomReservations{
    public static SRV_RoomReservations newInstance(){
        return ( SRV_RoomReservations ) dfflib.service.newInstance( SRV_RoomReservations.class );
    }

    // Service methods and implementation....
}
@RestResource( UrlMapping = '/Room/Cancellation/*' )
global with sharing class SRVi_RoomCancellation{
    @HttpPost
    global static void handleRequest(){
        // Integration magic
    }
}

Service Interface isn't a framework requirement

There is no framework need to construct an interface like IService. Examples including such, predate the Apex Stub API to enable mocking.

However, a Service could be likely to desire different implementations in the future (e.g. SRV_OpportunityRenewal for country or product family differentiations), where such interface would allow swapping implementations without changing the consuming code, leveraging dependency injection. This is thus a project- and business-specific need, not a framework mandate.

The naming in the metadata is a legacy convention and does not imply a strict requirement for an interface to exist.

Metadata registration

To ensure the newInstance() factory method resolves the correct class, the Service must be registered in the Dfflib_Service_Config__mdt custom metadata type . With the right AI skills, this metadata file can be automatically generated, else ensure to set the below values:

FieldPurposeExample
MasterLabelLabel of the mdt record. Shown in SetupSRV_RoomReservations
DeveloperNameUnique API name of the record. Doesn't allow duplicate (___) thus namespace with singleSRV_RoomReservations
Interface_Type__cInterface the Service is resolved bySRV_RoomReservations or SRV_RoomReservations.IService
Implementation_Type__cClass implementing the ServiceSRV_RoomReservations

Code examples

Since the Service layer isn't much more than a mockable layer, there are no standard or advanced methods to leverage. Every code-example we'd give is more a possible business process illustration than a strict guideline on how to leverage the Service layer. Below are therefore some examples of what a Service class might look like in practice, like SRVo_PostalCodeValidation.

ClassContext
SRV_RequestHTTP request builder
SRV_ResponseStandardised LWC & HTTP Response builder
SRVo_PostalCodeValidationOutgoing integration to validate postal codes
SRVo_PostalCodeValidationTestUnit test for outgoing integration

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_Service_Config__mdt record exists
  2. Change [Application].service.newInstance() to dfflib.service.newInstance()
public with sharing class SRVo_PostalCodeValidation{
    public static SRVo_PostalCodeValidation newInstance(){
        return ( SRVo_PostalCodeValidation ) dfflib.service.newInstance( SRVo_PostalCodeValidation.class );
    }
}
public with sharing class SRVo_PostalCodeValidation{
    public static SRVo_PostalCodeValidation newInstance(){
        return ( SRVo_PostalCodeValidation ) Application.service.newInstance( SRVo_PostalCodeValidation.class );
    }
}

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