Level: AdvancedSalesforce

Apex Enterprise Patterns: Service, Selector, Domain and Unit of Work

Updated 8 min read
Apex Enterprise Patterns featured image: title card with an Apex code example

Apex Enterprise Patterns split a large Salesforce app into clear layers: Service, Domain, Selector and Unit of Work. Each layer has one job, so queries, business rules and saving data never get mixed up in one giant class. Big teams use this structure to keep code readable for years.

In this post, you will learn what each layer does, how they call each other, and how to build a small version for courses at Bright Path Tutors. It builds on Apex Design Patterns, the trigger handler pattern and Apex bulkification.

What are Apex Enterprise Patterns?

Apex Enterprise Patterns are a layered architecture for Apex, based on Martin Fowler’s enterprise patterns and popularised by Andrew Fawcett. The open source fflib library gives base classes for each layer, although you can follow the ideas in plain Apex. The goal is separation of concerns, which means each class handles one kind of work.

Think of a restaurant. Waiters take orders (Service), chefs follow recipes (Domain), the store room hands out ingredients (Selector), and the cashier settles the bill once at the end (Unit of Work). Nobody does everyone’s job, so the kitchen runs smoothly even when busy.

Why Apex Enterprise Patterns Matter

Small orgs survive with simple classes, but large apps need structure. Here is why Apex Enterprise Patterns matter at Bright Path Tutors.

  • First, course rules are used by triggers, LWC, batch jobs and APIs.
  • Also, the same course query appears in ten places today.
  • Next, saving enrolments, payments and seats must happen in the right order.
  • New developers need to find logic quickly.
  • Finally, each layer can be tested and mocked on its own.

So the layers stop duplication and make large codebases safe to change.

How Apex Enterprise Patterns Work

A request moves through Apex Enterprise Patterns in a fixed order. First, an entry point, such as an LWC controller or trigger, calls a Service method. Next, the Service asks a Selector for the records it needs. Then it passes those records to a Domain class, which applies business rules. After that, the Service registers all changes with a Unit of Work. Finally, the Unit of Work commits every insert and update in one go.

Apex Enterprise Patterns diagram showing entry point, selector, domain, register and commit
How a request moves through the four layers.

Service Layer

The Service layer holds business processes, such as “apply discounts” or “enrol a student”. Entry points call it, so the same logic serves LWC, batch and REST.

Selector Layer

Selectors hold all SOQL for one object. So fields, filters and security live in one place.

Domain Layer

Domain classes hold rules for one object, such as validation and calculations. They also replace logic inside triggers.

Unit of Work

The Unit of Work collects inserts, updates and deletes, then saves them in the right order. As a result, DML stays bulk-safe and transactional.

The fflib Library

The open source fflib apex-common library supplies base classes for these layers. Teams can adopt it fully, or copy the ideas in simpler classes.

The Four Layers at a Glance

The table below sums up each layer and its rules.

LayerHoldsMust not
ServiceBusiness processesContain SOQL directly
SelectorSOQL for one objectChange records
DomainRules for one objectCall other services freely
Unit of WorkPending DMLHold business rules
Entry pointTrigger, LWC, APIContain business logic

Layered Apex vs One Big Class

The table below compares a layered design with a single large class.

FeatureLayered designOne big class
Finding logicClear place per concernSearch the whole file
ReuseAny entry point calls the serviceCopy and paste
TestingMock each layerTest everything together
Setup effortHigher at the startLow at the start
Best forLarge, long-lived appsSmall, short-lived features

When to use which depends on size. Use layers for apps with many developers or entry points. Keep small one-off features simple.

Apex Enterprise Patterns diagram comparing a layered design with one big class
Layered design vs one big class.

A Real Apex Enterprise Patterns Example

Let’s build a small version of Apex Enterprise Patterns at Bright Path Tutors. A Service applies a level-based fee change to selected courses.

Step 1: The Selector and Domain

public with sharing class CoursesSelector {
    public List<Course__c> selectByIds(Set<Id> ids) {
        return [SELECT Id, Name, Fee__c, Level__c
                FROM Course__c WHERE Id IN :ids WITH USER_MODE];
    }
}

public with sharing class CoursesDomain {
    private List<Course__c> records;
    public CoursesDomain(List<Course__c> records) { this.records = records; }

    public void applyLevelPricing() {
        for (Course__c c : records) {
            if (c.Level__c == 'Advanced') {
                c.Fee__c = (c.Fee__c * 1.10).setScale(2);   // 10% more
            }
        }
    }
}

The Selector owns the query and its fields. Then the Domain changes fees in memory only, so it never runs DML itself.

Step 2: The Service and a Simple Unit of Work

public with sharing class CourseService {
    public static void reprice(Set<Id> courseIds) {
        List<Course__c> courses = new CoursesSelector().selectByIds(courseIds);
        new CoursesDomain(courses).applyLevelPricing();

        SimpleUnitOfWork uow = new SimpleUnitOfWork();
        uow.registerDirty(courses);
        uow.commitWork();
    }
}

public with sharing class SimpleUnitOfWork {
    private List<SObject> dirty = new List<SObject>();
    public void registerDirty(List<SObject> recs) { dirty.addAll(recs); }
    public void commitWork() {
        Savepoint sp = Database.setSavepoint();
        try { update as user dirty; }
        catch (Exception e) { Database.rollback(sp); throw e; }
    }
}

The Service tells the story in four lines: select, apply rules, register, commit. Meanwhile, the Unit of Work rolls everything back if any update fails.

Step 3: Call It and See the Result

CourseService.reprice(new Set<Id>{ 'a01Kj00000Ab3xY', 'a01Kj00000Ab3xZ' });

Here is the result in the debug log.

UPDATE Course__c: 2 rows
Advanced LWC Patterns: 7200.00 -> 7920.00
Apex Basics (Beginner): 5000.00 (no change)

An LWC controller, a batch job and a REST service can all call the same Service method. So the pricing rule lives in exactly one place.

Apex Enterprise Patterns and Testing

Because each layer has one job, tests stay small. For example, you test the Domain with in-memory records and no DML at all. With fflib, you can also mock Selectors and the Unit of Work, so Service tests run fast.

Common Mistakes with Apex Enterprise Patterns

  • Writing SOQL inside Service or Domain classes.
  • Running DML in Domain methods instead of the Unit of Work.
  • Putting business logic back into triggers or controllers.
  • Adopting every fflib feature on a tiny project.
  • Creating one Service per object instead of per business process.

Best Practices for Apex Enterprise Patterns

  • Name services after business processes, such as EnrolmentService.
  • Keep all queries for an object in its Selector.
  • Keep Domain methods free of DML.
  • Commit once per transaction through a Unit of Work.
  • Introduce layers step by step in existing code.

Practice Task

Add an EnrolmentService.enrol method that creates an enrolment and reduces course seats in one Unit of Work. Hint: add registerNew to SimpleUnitOfWork and insert new records before updates.

Most Asked Interview Questions on Apex Enterprise Patterns

Architecture questions are common for senior roles. Here are the 21 questions asked most about Apex Enterprise Patterns.

Basic Questions on Apex Enterprise Patterns

Q1: What are Apex Enterprise Patterns?

They are a layered Apex architecture with Service, Domain, Selector and Unit of Work layers.

Q2: What does separation of concerns mean?

Each class handles one kind of work, so changes stay local.

Q3: What does the Service layer do?

It runs business processes and coordinates the other layers.

Q4: What does a Selector do?

It holds all SOQL for one object, so queries are reused.

Q5: What does a Domain class do?

It applies business rules for one object, usually in memory.

Q6: What is the Unit of Work?

It collects DML and commits it once, in the right order.

Q7: What is fflib?

It is an open source library that supplies base classes for these layers.

Code and Scenario Questions on Apex Enterprise Patterns

Q8: Where should a trigger send its logic?

To a Domain class or Service, so the trigger stays one line.

Q9: Why should Domain classes avoid DML?

Because DML belongs in the Unit of Work, so saves stay bulk-safe.

Q10: How do several entry points share logic?

They all call the same Service method.

Q11: How does a Unit of Work handle parent and child inserts?

It inserts parents first, then sets child lookups and inserts children.

Q12: How do you add security to selectors?

Use WITH USER_MODE or the selector’s built-in security checks.

Q13: How do you test a Service without real data?

Mock the Selector and Unit of Work, so the test checks only the logic.

Q14: When would you skip these patterns?

For small, short-lived features where layers add more cost than value.

Advanced Questions on Apex Enterprise Patterns

Q15: How do the layers help with governor limits?

Queries and DML happen once per layer, so code stays bulkified.

Q16: What is the Application factory in fflib?

It maps interfaces to classes, so you can swap implementations and mocks.

Q17: Should services be static or instance?

Many teams use static facades over instance classes, so they can inject mocks.

Q18: How do you migrate a legacy org to these patterns?

Start with new features and the busiest objects, then refactor step by step.

Q19: Where do callouts belong?

In a service or a dedicated integration class, never in Domain classes.

Q20: How do Domain classes relate to triggers?

The trigger calls the Domain, which runs logic per trigger event.

Q21: What is the main cost of this architecture?

More classes and setup, so the team must agree on the rules.

Official Resources

Quick Recap

  • Using Apex Enterprise Patterns splits code into four layers.
  • Services run processes, and Selectors hold queries.
  • Domains hold rules, and the Unit of Work commits DML.
  • Entry points stay thin and call services.
  • Use layers for large apps, not small features.

What’s Next?

Rules often need to change without code. Next, read our guide to custom metadata in Apex.