Concept 3 of 10Design and best practices

Apex design patterns: layers, unit of work, strategy and factory

Separation of concerns (service, domain, selector), unit of work, strategy and factory for variation, dependency injection for tests, and the per-transaction cache.

Your confidence:Not rated

Simple explanation

Large orgs fail from tangled code, not from missing features. A few patterns keep it maintainable.

Enterprise layers (popularised by the Apex Enterprise Patterns and the open-source fflib library):

  • Service layer: business operations (OrderService.submit(orderIds)). Called from triggers, Flows, LWC, APIs and batch jobs alike. Bulk by design.
  • Domain layer: behaviour and validation for one object (Opportunities.onBeforeUpdate()), usually invoked from the trigger handler.
  • Selector layer: all queries for an object in one class, with consistent fields and security.
  • Unit of Work: collects inserts, updates and deletes, resolves relationships between new records, and commits them in the right order in one place.

Patterns for variation and testing:

  • Strategy: one interface, several implementations chosen at runtime (for example a pricing rule per country).
  • Factory / dependency injection: code asks for an interface and gets the implementation from a factory or custom metadata, so tests can inject a mock.
  • Singleton / per-transaction cache: a static variable holds data loaded once per transaction (for example the current user's settings).
  • Builder in tests for readable test data.

You don't need every layer for every org. Use service + selector as a minimum in any org with real code, and add the rest when complexity justifies it.

Real-world analogy

A restaurant kitchen. The waiter (trigger, LWC, API) takes orders but never cooks. The head chef (service) decides what happens. Station chefs (domain) know how to handle their own ingredient. The pantry (selector) is the only place ingredients come from. The pass (unit of work) sends complete plates out together, in the right order.

Worked example

Strategy + factory for country-specific discount rules, chosen from custom metadata:

public interface DiscountStrategy {
    Decimal discountFor(Opportunity opp);
}

public with sharing class StandardDiscount implements DiscountStrategy {
    public Decimal discountFor(Opportunity opp) {
        return opp.Amount != null && opp.Amount > 100000 ? 0.05 : 0;
    }
}

public with sharing class PublicSectorDiscount implements DiscountStrategy {
    public Decimal discountFor(Opportunity opp) {
        return 0; // framework agreement prices are already net
    }
}

public with sharing class DiscountStrategyFactory {
    @TestVisible
    private static Map<String, DiscountStrategy> overrides = new Map<String, DiscountStrategy>();

    public static DiscountStrategy forSegment(String segment) {
        if (overrides.containsKey(segment)) {
            return overrides.get(segment);           // tests inject mocks here
        }
        Discount_Rule__mdt rule = Discount_Rule__mdt.getInstance(segment);
        String className = rule != null ? rule.Strategy_Class__c : 'StandardDiscount';
        Type t = Type.forName(className);
        if (t == null) {
            throw new IllegalArgumentException('Unknown discount strategy: ' + className);
        }
        return (DiscountStrategy) t.newInstance();
    }
}

Selector with consistent fields and user-mode access:

public inherited sharing class AccountsSelector {
    public List<Account> selectWithOpenOpportunities(Set<Id> ids) {
        return [
            SELECT Id, Name, Segment__c,
                   (SELECT Id, Amount, StageName FROM Opportunities WHERE IsClosed = false)
            FROM Account
            WHERE Id IN :ids
            WITH USER_MODE
        ];
    }
}

Diagram

Rendering diagram…

Key points

  • Service layer = one entry point for a business operation, reused by triggers, Flow, LWC, APIs and batch.
  • Selector layer = all queries for an object in one place, with consistent security.
  • Domain layer = object-specific behaviour; Unit of Work = ordered, single commit.
  • Strategy + factory handle variation (country, segment) without if chains; custom metadata chooses the class.
  • Dependency injection through interfaces makes unit tests fast and isolated.
  • Apply patterns in proportion to complexity; service + selector is a sensible minimum.

Limits and gotchas

  • Over-engineering a small org with every fflib layer slows the team down. Introduce layers when there are several entry points or developers.
  • Type.forName + newInstance need a public no-argument constructor, and the class name in metadata must be kept in sync (test for it).
  • Static variables live for one transaction only. They are a cache, not shared state across users or jobs.
  • A Unit of Work hides DML timing. Developers must understand that nothing is written until commitWork().

🎀 How to say this in an interview

"How would you structure the code in a large org?" is a standard architect question. Show the layered diagram, explain why the service layer makes Flow, LWC and integrations reuse the same logic, and give one concrete pattern (strategy for country rules) with its testing benefit.

Common follow-ups

How do you expose a service method to Flow?

Wrap it in an @InvocableMethod that accepts a list of request objects and returns a list of results. The invocable is thin: it maps inputs, calls the bulk service method once and maps outputs. Flow calls it in bulk when many records are processed.

Would you use fflib in a new project?

If the team knows it and the org is large with many developers, yes: it's proven and gives consistent layers. For a smaller team, a lightweight service + selector + trigger-handler structure gives most of the benefit with less ceremony. Agree the conventions in a coding standard either way.