# Welcome to the D'fflib documentation URL: /dfflib/docs/welcome/ Here you find what and why we open-sourced, and how to maximise this framework's benefits. The aim of this (documentation) website is to: **Explain the benefits and essentials of both fflib and D'fflib**\ Both for technical and non-technical stakeholders, to understand why adopting (D')fflib is a prerequisite for sustainable and maintainable Salesforce implementations (and thus reducing long-term costs). **Elaborate on the origin, reasoning and purpose of D'fflib**\ Where the extensions originated, the collaboration with Apex Enterprise Patterns core team and the aim to contribute back and collaborate with the Salesforce developer community. **Provide one centralised place for your (D')fflib learning and documentation**\ There are various articles and websites, though quite often this only encourages copy-pasting. Our belief is to make the complex simple(r) by clear and extensive examples and elaborating on the reasoning. To navigate, browse the menu (structured by the three main questions: **Why**, **What** and **How**) or use the search functionality (`CTRL + K`). To help you out, here are some quick links to get you started: If you can't find what you're looking for, reach out via [one of the channels in the Support page](/dfflib/docs/how/support#channels). --- # Business benefits URL: /dfflib/docs/why/business-benefits/ D'fflib unlocks scalable and maintainable applications which can significantly reduce your delivery overhead. D'fflib is a free, easy-to-install, community-driven framework\ that enables organisations to build scalable and maintainable Salesforce code.\ Leading to reduction of delivery overhead, time-to-market and maintenance costs.\ It extends the proven 'fflib' framework, focusing to enable developers.\ Significantly extending the framework, improving the performance and simplifying adoption and application. Despite having the best developers on your team, it will always remain a challenge to refactor and debug logic that was written by someone else some time ago. This is a known challenge for the stability of your applications, and can negatively impact the delivery velocity, throughput time and increase costs. `fflib` is a proven coding framework that guides developers to structure their code in a way that is easier to understand, maintain, and extend over time. Thanks to this structure, new team members can quickly get up to speed, and existing team members can work more efficiently. D'fflib is a significantly enriched version of the original `fflib` and not only applies the theory but also focuses on relaxing and enabling the developers, reducing the time to learn, adopt and apply the framework. ## Main benefits [#main-benefits] ### Reduced delivery overhead [#reduced-delivery-overhead] With a well-defined structure, developers can quickly understand existing codebases and implement new features. This modular and structured setup helps to reduce time for debugging and onboarding new team members, which results in shorter development cycles and quicker time-to-market for new functionalities. ### Reduced time to delivery [#reduced-time-to-delivery] Both by the improved maintainability and scalability of the code, the acceleration by preventing the need to re-invent the wheel with some pre-setup and tested frameworks, and also by the significant reduction of unit test runtime which runs on deployments. ### Reduced maintenance costs [#reduced-maintenance-costs] fflib helps to minimise technical debt by guiding developers to apply best-practices and eliminate the need for writing duplicate and repetitive code. This leads to cleaner, more efficient code that automatically applies industry standards like security enforcement and exception handling. ### AI-enabler for fewer tokens and more accurate responses [#ai-enabler-for-fewer-tokens-and-more-accurate-responses] A well-structured and consistently organised codebase directly benefits AI-assisted development. AI tools need less context to understand your code, reducing token usage and costs. Combined with D'fflib's full documentation and a set of ready-to-apply AI skills, AI tools can provide faster, more accurate and thus cheaper responses. [→ Check FAQ for coding framework relevancy in AI era](/dfflib/docs/faq#relevancy-ai) ### Fit-for-the-future [#fit-for-the-future] Structuring your codebase with the patterns shipped with (D')fflib, ensures your code is scalable, modular and maintainable. Code is structured in smaller, bulkified and reusable services, preparing for easier extension and re-use for emerging technologies, like Headless CRM and MCPs. *Note: (D')fflib provides the structure, which still needs to be applied and respected by developers for success.* ## Distinction between D'fflib vs. fflib [#distinction-between-dfflib-vs-fflib] * **fflib** (`apex-common`) is the proven open-source framework launched by Andrew Fawcett around 2014 from FinancialForce. Focusing to enable the theoretical implementation of Apex Enterprise Design Patterns in Salesforce development. * **D'fflib** is a significantly enriched extension on top of fflib, which focuses on truly enabling developers in their development and the onboarding and utilisation of this framework. Most of the benefits shared above are applicable to both `fflib` and D'fflib and we would always recommend to at least apply `fflib`. To further unlock the potential and support your developers we believe D'fflib can help ease their work even more, while leveraging some serious performance improvements for your end-users. Hence, below you find some links and numbers to help understand the differences. * Focused on enabling developers, an extended framework, tailored to reduce lines of (repetitive) code * Enabling developers with all latest Salesforce feature * Significant performance improvements (for your end-users) * Simplified and standardised usage, flattening learning and adoption curve * Resolving several known fflib challenges * Simple install and upgrade via (unlocked) package link * Only one package to maintain, reducing technical debt and dependencies *→ Click to see all benefits.* * D'fflib provides full documentation (for both fflib and D'fflib) on edge cases or basic steps * D'fflib provides AI-skills to enable developers and their agents * The active community ensures continuity in improvements, like adopting the latest Salesforce features * With the unlocked package urls newer versions can be swiftly installed or upgraded *→ Click to read more about available support.* D'fflib comes with multiple shortcuts, accelerators and built-in frameworks to fully support your developers, without the need to repetitively duplicate code or custom-build a framework to support common functionalities. *→ Click to read more about our accelerators, shortcuts and built-in frameworks.* * Using D'fflib makes each database interaction \~14x faster than the original fflib. * Both frameworks guarantee proper error handling and transaction management ensuring data integrity. Without the need for a developer to consciously repeat its code, as it's automatically applied. * Both frameworks enable bulkified database interactions, eliminating overhead and risk of hitting governor limits. * A proper fflib implementation can reduce your full Unit Test runtime by 40-50%. * D'fflib even unlocks an additional 10-20%, due to framework enrichments. This is realised by 'mocking' methods during unit tests, avoiding unnecessary executions and only validating the single-responsibility of the method being tested. ## Implementation efforts [#implementation-efforts] Efforts might vary per organisation depending on the current codebase, team experience, and project complexity. **Install** (5 min) or **upgrade** (1 day)\ D'fflib comes with an easy unlocked package install-link, which allows you to install within a couple minutes. Additionally, D'fflib is fully backward compatible with the original fflib (apex-common) framework, allowing for an easy upgrade path within approx. one day. An upgrade from a previous D'fflib version is feasible within minutes. **Training**\ This completely depends on the experience of your developers with layered architectures and/or other frameworks. The proper adoption of fflib requires the understanding of some more abstract concepts and therefore it's recommended to have some senior developers trained, to allow them to guide others (this is possible given the possible phased roll-out and application of the framework). In addition to this extensive documentation website, we also provide [training sessions](/dfflib/docs/how/support#tailored-trainings) (4 hours to 2 days, depending on demand). **Phased roll-out** (weeks to months)\ Depending on your current codebase there are different strategies to roll-out fflib. 1. Foundational: Move low-increment changes to fflib first, having the structure set up and first files created 2. New development: Apply fflib only on new development work, gradually increasing the coverage 3. Full refactor: Move all existing code to fflib in one go Each strategy has its pros and cons, and the choice depends on your organisation's priorities and resources. In doubt what strategy to apply? Our [fflib tailored maturity assessment](/dfflib/docs/how/support#maturity-assessment) can help to understand your status quo, and provide concrete actions including their potential (business) benefits. ## Frequently asked (business) questions [#frequently-asked-business-questions] For questions on how D'fflib makes code more reusable, or what 'dependency' there is to Deloitte, [→ visit the FAQ page](/dfflib/docs/faq) (as we'd like things centralised). --- # Technical benefits URL: /dfflib/docs/why/technical-benefits/ Overview of the most important benefits and considerations for implementing D'fflib as an architect or developer. D'fflib helps developers to excel in their deliveries, ensuring scalable, maintainable and testable Salesforce code. It extends the proven `fflib` (`apex-common`) framework, but focuses on enabling developers while tackling some known challenges, significantly extending the framework and improving performance. Most developers know that feeling when looking back at their old code: recognising how far they've come, but also spotting the design choices they'd make differently now with more context and less time pressure. This becomes even more complex when joining an existing team and having to piece together an entire codebase and all the decisions that shaped it, from scratch. It's therefore no surprise that multiple cross-language principles and guidelines have risen (such as [Object Oriented Programming](https://en.wikipedia.org/wiki/Object-oriented_programming), [Model-View-Controller](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) and [Unit of Work](https://martinfowler.com/eaaCatalog/unitOfWork.html)) to help structure codebases and keep them maintainable. `fflib` ([apex-common](https://github.com/apex-enterprise-patterns/fflib-apex-common)) helps to apply the theories of Single Responsibility Principle and [Apex Enterprise Design Patterns](https://trailhead.salesforce.com/users/rvandenassum/trailmixes/apex-enterprise-design-patterns) (Layered Architecture) in Salesforce development. When properly applied this leads to more maintainable, scalable and testable code; which is significantly easier to understand and extend (by others). D'fflib is a significant extension on top of `fflib` to focus on enabling developers to adopt and apply it faster and more easily. It provides technical enhancements, performance improvements, and shortcuts to reduce the number of (repetitive) code lines and the time needed to learn the framework to deliver effective and modular code. It is released as an extension after close alignment and collaboration with the Apex Enterprise Patterns (AEP) core team (maintaining `fflib`). Providing you two (unlocked) packages: 1) the full package, including `apex-common` and `apex-mocks` and thus reducing technical debt for package management etc; or 2) the "D'fflib only" package, which only ships our extensions, to keep control of which fflib version is used (e.g. with customisations), thus also owning full dependency control. ## Main benefits [#main-benefits] ### Understandable and maintainable code [#understandable-and-maintainable-code] By the well-defined structure, every developer becomes able to - more easily - find functionalities, even when delivered by another team (member). The framework supports a guided application of industry standards, but doesn't enforce it (allowing a phased rollout). This results in modular, easier-to-read and maintainable code. ### Unlocking scalable and testable applications [#unlocking-scalable-and-testable-applications] Applying `fflib` unlocks out-of-the-box mocking support, enabling a significant reduction in unit test runtime (40-50%, up to 60% with D'fflib's additional framework enrichments) while strengthening unit test quality through simplified testing. Due to the Single Responsibility Principle, each test only needs to validate the method's own functionality and can disregard (mock/fake) other consumed methods, as those are covered in their own unit tests. ### Accelerators, frameworks and less repetitive code [#accelerators-frameworks-and-less-repetitive-code] While Apex already takes care of quite some stuff (like memory management) there is still quite some repetitiveness in writing code like exception handling and security enforcement. `fflib` helps to reduce this with pre-built structures and base-classes, allowing developers to focus on the actual business logic. D'fflib even takes this a step further by providing additional [accelerators](/dfflib/docs/what/accelerators-utilities) and frameworks (like for [Trigger Handlers](/dfflib/docs/what/trigger-framework) and [Test Data Builder Framework](/dfflib/docs/what/test-factory-builder-framework)). This way developers can focus on 'the fun stuff', while reducing lines of code and thus delivering more readable solutions. ### AI enabler for faster, more accurate, first-time-right AI-responses [#ai-enabler-for-faster-more-accurate-first-time-right-ai-responses] D'fflib's consistent structure and clear separation of concerns give AI tools unambiguous context about your codebase. LLMs can recognise and understand well-known architectural patterns and therefore more easily locate the right components and generate accurate, targeted results without having to understand the entire codebase for each prompt. While additionally reducing the risk of an AI-generated change to unintentionally impact other areas. With the full documentation website and a set of ready-to-apply AI skills, you're directly enabled to leverage all AI-benefits while reducing repetitive back-and-forth and token usage. ### Significant delivery and performance improvements [#significant-delivery-and-performance-improvements] D'fflib provides some significant performance improvements ([>14x faster database interactions](/dfflib/docs/what/unit-of-work) compared to `fflib`), while allowing calling classes to define the sharing/database context the logic should run with. This eliminates the need for local project customisations with own `IDMLs` or `without sharing` inner classes. Additionally, this resolves the challenge of `fflib` where selector methods can't be tested. ### Fit-for-future [#fit-for-future] Being fully [metadata driven](/dfflib/docs/what/metadata-driven) D'fflib allows you to split codebases into smaller packages. This can modularise your application and enable autonomous development cycles with scratch orgs etc, while reducing dependencies between teams. ### Up-to-date & community-driven [#up-to-date--community-driven] Both `fflib` and D'fflib are open-source frameworks, allowing anyone to contribute. While fflib was initiated by Andrew Fawcett and D'fflib by Deloitte, there is no restriction or limitation to these founders. This community interaction ensures the framework is kept up-to-date with latest best-practices and features, but also ensures edge cases can be openly discussed and aligned upon. ## Framework details [#framework-details] * Focused on enabling developers, an extended framework, tailored to reduce lines of (repetitive) code * Enabling developers with all latest Salesforce feature * Significant performance improvements (for your end-users) * Simplified and standardised usage, flattening learning and adoption curve * Resolving several known fflib challenges * Simple install and upgrade via (unlocked) package link * Only one package to maintain, reducing technical debt and dependencies *→ Click to see all benefits.* * D'fflib provides full documentation (for both fflib and D'fflib) on edge cases or basic steps * D'fflib provides AI-skills to enable developers and their agents * The active community ensures continuity in improvements, like adopting the latest Salesforce features * With the unlocked package urls newer versions can be swiftly installed or upgraded *→ Click to read more about available support.* ## Implementation efforts [#implementation-efforts] Efforts might vary per organisation depending on the current codebase, team experience, and project complexity. **Install** (5 min) or **upgrade** (1 day)\ With the unlocked package link, installation and future updates are only a matter of minutes. Upgrading from `fflib` does require some steps, but is [fully documented](/dfflib/docs/how/get-started), like an Anonymous Apex script to automatically generate the metadata records based on the existing Application class. **Training**\ This completely depends on the experience of your developers with layered architectures and/or other frameworks. We recommend ensuring some senior developers are trained first, allowing them to guide others while gradually adopting the framework in your codebase. This can be by [Trailheads](https://trailhead.salesforce.com/users/rvandenassum/trailmixes/apex-enterprise-design-patterns) or the materials on this website. If desired, we are happy to support, e.g. with [training sessions](/dfflib/docs/how/support#tailored-trainings) (4 hours to 2 days, depending on demand). **Phased roll-out** (weeks to months)\ Depending on your current codebase there are different strategies to roll-out fflib. 1. Foundational: Move low-increment changes to fflib first, having the structure set up and first files created 2. New development: Apply fflib only on new development work, gradually increasing the coverage 3. Full refactor: Move all existing code to fflib in one go Each strategy has its pros and cons, and the choice depends on your organisation's priorities and resources. In doubt what strategy to apply? Our [fflib tailored maturity assessment](/dfflib/docs/how/support#maturity-assessment) can help to understand your status quo, and provide concrete actions including their potential (business) benefits. --- # Open-sourcing D'fflib URL: /dfflib/docs/why/dfflib-open-source/ Why Deloitte decided to open-source their enriched version of fflib. Deloitte decided to open-source our enriched version to contribute back to the community, connect with other passionates, simplify an intellectual property challenge and connect with organisations who might welcome support. ## Rationale to open-source [#rationale-to-open-source] ### Significant enrichments [#significant-enrichments] Since 2016 we have been applying and extending the original fflib (apex-common) framework within our projects. This resulted in quite some significant changes like a full trigger and test factory builder framework and multiple efficiency improvements, both performance and developer usage wise. ### Challenges to contribute back [#challenges-to-contribute-back] The Apex Enterprise Patterns (AEP) repositories operate under a different mindset, with a hard backward-compatibility requirement and different framework principles regarding intentional design for theoretical correctness. Combined with limited response and activity on contributions over the past years, Deloitte, then, consciously decided to release D'fflib separately, as a full framework of its own. The AEP Core team responded positively to our initial outreach, acknowledging the different framework principles and responsiveness, and requested to position D'fflib as an extension rather than a replacement, as this would avoid confusion in the Apex Developer Community. After some careful consideration and successful collaboration, all pre-requisites were met to ensure clear separation of concerns. Allowing us to offer our enrichments with the community, without acting as a replacement for `fflib`. ### Resolve intellectual property challenge [#resolve-intellectual-property-challenge] When applying D'fflib in our projects, we always faced 'intellectual property' challenges when collaborating with other implementation vendors, or returning maintenance to the client. We didn't want to commercialise the framework, given our gratitude to the original open-sourcing of the FinancialForce-based library. By open-sourcing, we mitigate these challenges, as D'fflib becomes community-driven, and thus not tied to any single entity's intellectual property. ### Quality & Collaboration in Developer community [#quality--collaboration-in-developer-community] We are proud of our focus for quality by our strong developer community, and are happy to share that to the public. We would love to see this framework become community-driven (only initiated by Deloitte) and strengthen this joined framework even further by combining the passion for 'proper code' and improving the overall quality of Salesforce deliveries to eventually improve platform customer satisfaction. ### Offer supporting hand [#offer-supporting-hand] Based on individual responses, we've noticed quite some organisations do implement fflib, but struggle with the proper adoption and gaining the full benefits. Either by limited team knowledge, simply not knowing where to start/what full benefits could be, or not having a clear defined approach in combination with limited capacity. To those organisations we would like to offer support by means of this extensive documentation, or * Automated scan to identify current maturity of your (D')fflib implementation * Report with concrete steps and corresponding benefits these would unlock, incl. voice-over * Optional interviews with your development team to properly understand their challenges/approach. *Click for more info.* Depending on your need we can provide tailored training sessions (remote or on-site) to get your team enabled to maximise usage of the framework. *Click for more info.* --- # Other alternatives URL: /dfflib/docs/why/comparison/ Highlighting benefits and challenges from other well-known Apex coding frameworks. We understand that different projects have different needs, and we encourage architectural evolution over time. However, to avoid architectural drift, and based on our experience that every codebase eventually grows driven by business demand, we'd always suggest a solid framework like (D')fflib for any project. This reduces ambiguity, enforces separation of concerns, and provides a sustainable structure that stands the test of time. ## The Apex architecture landscape [#the-apex-architecture-landscape] Over time, we've seen three broad categories of architectural guidance emerge in the Salesforce Apex ecosystem, each with a different philosophy and trade-off profile: * **Frameworks** (e.g. D'fflib, `fflib`) impose a layered structure upfront, reducing ambiguity and enforcing separation of concerns across the entire codebase. *Trade-off: more code, steeper initial learning curve, less flexibility for small projects.* * **Principles** (e.g. `AWAF`) provide guiding philosophies that teams interpret and apply independently, prioritising flexibility and developer autonomy. *Trade-off: harder to apply consistently across teams; divergence grows over time.* * **Libraries** (e.g. `Force DI`, `SOQL-Lib`, `Apex Fluently`) provide targeted utilities that solve specific problems and can be composed alongside any architectural approach. *Trade-off: no structural guidance; integration, compatibility and dependency maintenance are your responsibility.* In our experience, **no codebase stays simple forever** — the architectural decisions made early tend to compound, for better or worse, as teams and requirements grow. As Andrew Hunt & David Thomas famously observed in [***The Pragmatic Programmer***](https://en.wikipedia.org/wiki/The_Pragmatic_Programmer): > No one in the brief history of computing has ever written a piece of perfect software. It's unlikely that you'll be the first. It is with that reality in mind that we explore the approaches available to Apex development teams today. The table below compares these categories across dimensions, providing references to deep-dives later on the page, and [a table of alternatives](#architectural-guidances-compared) used for this article at the end. | Dimension | Frameworks
e.g. [fflib](https://github.com/apex-enterprise-patterns/fflib-apex-common), D'fflib | Principles
e.g. [AWAF](https://www.awaf.dev/) | Libraries
e.g. [Force DI](https://github.com/apex-enterprise-patterns/force-di), [SOQL-Lib](https://soql.beyondthecloud.dev/) | | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | **Ambiguity / Objectivity** | Low ambiguity — shared conventions make [code reviews objective](#review-objectivity-and-rogue-classes) | Higher ambiguity — principles require interpretation, leading to [divergent implementations](#structural-divergence-across-projects) | N/A — libraries solve specific problems, not structural ambiguity | | **Onboarding time** | Weeks — structured [onboarding path](#documentation--onboarding) via external resources (Trailhead, books, community) | Weeks — team-specific docs required; no shared external reference | Days — typically low for individual tools | | **Junior developer paradox** | Framework scaffolding [accelerates growth](#the-junior-developer-paradox) — "put this logic here" is actionable | Principles require interpretation before application — harder for developers still building mental models | Not applicable at the architectural level | | **Maintenance / Dependency** | Single external dependency, [one provider](#alternative-approaches--the-assembly-trade-off) — trust one established codebase | Requires assembling 3–5 utilities with independent release cycles; principles often additionally recommend library adoption, increasing the total dependency surface | Each library has its own maintainer and roadmap — integration is your responsibility | | **Documentation** | Powered by [external resources](#documentation--onboarding) — Trailhead, books, community posts supplement internal docs | Each team's unique approach requires bespoke documentation | Library-specific docs only; no cross-library architectural narrative | *** ## Exploring Apex architecture options [#exploring-apex-architecture-options] With the landscape above as context, the rest of this page examines where D'fflib excels, where the trade-offs become visible, and how the alternatives compare in practice. ### What D'fflib is designed to solve [#what-dfflib-is-designed-to-solve] At its core, D'fflib originates from **conventional enterprise application architecture**, where layered systems are used to control complexity. The framework's philosophy is to impose structure early, to reduce ambiguity and to prevent architectural drift as teams and codebases grow. Its purpose is not developer convenience — it is **system stability at scale**. The core problems it addresses are consistent across every enterprise Salesforce engagement we've been part of: * **Uncontrolled growth** of business logic * **Lack of architectural consistency** across teams * **Slow, database-dependent** test suites * **Long-term maintainability risk** as systems scale These aren't hypothetical risks — they're the most common reasons mature Salesforce orgs become *expensive to change*. For a deep-dive into each, see our [Technical benefits](/dfflib/docs/why/technical-benefits) and [EDP & fflib](/dfflib/docs/what/fflib-enterprise-design-patterns) pages. ### How it creates value over its compromises [#how-it-creates-value-over-its-compromises] D'fflib is designed to help teams manage complexity as systems grow, but that strength also brings trade-offs worth understanding before adoption. *** ## Addressing common framework challenges [#addressing-common-framework-challenges] Approaches like AWAF champion *principles over structure*, which is a philosophy that works well for teams with strong architectural alignment. Below we examine the most common challenges that arise in practice. AWAF's principle-driven approach is designed to give teams freedom to find their own "vibe." We respect that intent. In practice, though, that freedom means **every project will interpret and apply those principles differently**. Over time, that divergence is likely to incur organisational costs, due to steeper learning curves, longer onboarding times and team discussions on the proper principle application. Our recommendation remains D'fflib for most enterprise projects, precisely because it converts that freedom into a **shared, navigable structure**. ### Structural divergence across projects [#structural-divergence-across-projects] When each project finds its own structural interpretation, the codebase of Project A will look *meaningfully different* from Project B. Even if both teams followed the same principles in good faith. Moving a developer between projects requires significant ramp-up time to understand the local conventions, abstractions, and design decisions that emerged organically. With D'fflib, fewer iterations are needed to reach an empowering structured base. Patterns are **recognisable across codebases**, and developers transition more quickly because the framework, not the team's interpretation of principles, defines the structure. This matters especially for organisations staffing multiple Salesforce projects simultaneously. ### The junior developer paradox [#the-junior-developer-paradox] A common argument is that frameworks are *harder to learn* than principles, especially for the self-taught admins and business analysts who make up a large portion of the Salesforce ecosystem. We'd argue the opposite is often true. Principles require interpretation: a developer must first understand the principle, then decide how to apply it in their specific context, then defend that decision in a code review. A framework requires application: *"put this type of logic here."* That strictness is not a limitation, it is **scaffolding**. Developers grow *through* it, not despite it, and they reach the next seniority level more easily because the framework gives them a clear structure to discuss, challenge, and eventually transcend. *For a deeper look at how D'fflib supports developers at different seniority levels see [Guidelines → FAQ → Who are these guidelines for?](/dfflib/docs/how/guidelines#frequently-asked-questions)* ### Review objectivity and "rogue classes" [#review-objectivity-and-rogue-classes] Without a shared framework, code reviews become *debates about intent*. *"Is this separation of concerns correct?"* is a subjective question, where the answer depends on how each reviewer interprets the underlying principle. Well-intentioned developers applying principles independently can produce **"rogue classes"** that are structurally sound by their own reasoning but inconsistent with the rest of the codebase. Framework-based reviews are more objective: *"Does this query belong in the Selector?"* is a verifiable question. Reviews become **teaching moments** grounded in shared conventions, not hunches, and that consistency compounds over time as the team grows. ### Documentation & onboarding [#documentation--onboarding] Each team's unique architectural approach requires its own documentation and onboarding materials. A shared framework is powered by **external resources**, like Trailhead modules, books, community posts, supplemented by internal documentation which all *reduce onboarding burden*. Both approaches produce working software. The question is which **learning path** fits your team's composition and growth goals. Junior developers can't be expected to read principles and independently internalise how to apply them. A framework gives them **comparable classes to study**, a predictable structure to reason about, and code reviews grounded in shared conventions rather than individual judgement. Over time, developers absorb the *why* by living it, and once they understand the framework deeply enough to challenge it, they've already grown into the seniority level where that challenge is productive. One of the most concrete expressions of this is how D'fflib handles the boundaries between its own layers (particularly how Services and Domains interact), and how the framework approaches dependency injection. Rather than prescribing rigid rules, D'fflib provides *vocabulary for ongoing team discussion*. [Read more on the Services layer](/dfflib/docs/how/services) page. *** ## Alternative approaches & the assembly trade-off [#alternative-approaches--the-assembly-trade-off] One critique of D'fflib is the dependency on external code — *"importing a tool where maintenance is not guaranteed"*. This is a fair concern worth examining honestly. For a full overview of compared architectural guidances, see [Architectural guidances compared](#architectural-guidances-compared) below. Assembling an architecture from multiple independent libraries — each with its own maintainer, release schedule, and roadmap — introduces a maintenance surface that is often *larger* than adopting a single unified framework. Connecting those libraries, keeping them updated, managing version compatibility between them, and absorbing the risk of any one losing active support are all costs that land on your team. With D'fflib, you trust **one established ecosystem** with 10+ years of production validation. With an assembled stack, *you own the integration*. Neither approach eliminates maintenance risk entirely, so the question is **where that risk lives** and who manages it. *** ## Architectural guidances compared [#architectural-guidances-compared] The following table offers a structured overview of alternatives for teams with different constraints, inspired by the [Harrier documentation's discussion](https://docs.goharrier.com/technical/frameworks/fflib-apex-framework#alternatives): | Alternative / Pattern | Type | When It Fits | | ---------------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Apex Fluently](https://apexfluently.dev/) | Utility | A set of single-class injectable utilities for targeted functionality. Useful alongside any architectural pattern for teams wanting lightweight, composable utilities. | | [AT4DX/Apex Framework Patterns](https://github.com/apex-enterprise-patterns/at4dx) | Framework | A broader set of best practices for folder structure, naming conventions, and intent. Especially once an organisation has settled on how it wants to evolve its architecture. | | [AWAF (Apex Well-Architected Framework)](https://www.awaf.dev/) | Principles | Teams that prefer progressive adoption over upfront architectural overhead, with a *how code feels and reads* mindset. Best suited for small- to mid-projects emphasising clean code and Salesforce-first pragmatism. Note: teams must maintain 3–5 separate utilities with independent release cycles. | | [fflib Apex Extensions (Wim Velzeboer fork)](https://github.com/wimvelzeboer/fflib-apex-extensions?tab=readme-ov-file) | Framework | Teams that want D'fflib *plus* a richer set of patterns and helpers to reduce repetitive boilerplate without abandoning architectural discipline. | | [Force DI (Dependency Injection)](https://github.com/apex-enterprise-patterns/force-di) | Utility | When your primary need is dependency management to inject mocks cleanly without adopting a full architectural framework. | | [SOQL-Lib](https://soql.beyondthecloud.dev/) | Utility | Not an architectural framework; a focused utility. Use it *alongside* any architectural pattern to reduce SOQL complexity and duplication. | Each alternative occupies a different part of the architecture vs utility vs principle trade-off space. Understanding where your pain points lie helps in choosing the right blend. We understand that different teams have different constraints, and we encourage evolution over time. However, based on our experience, **D'fflib remains the approach that most consistently reduces that overhead** and we'd always recommend starting there. *** ## Our final thoughts [#our-final-thoughts] Architecture is not a one-size-fits-all decision. Team size, org maturity, domain complexity, and expected lifespan all play a role. Most approaches in the Salesforce ecosystem exist to solve the same underlying problem: keeping codebases **understandable, testable, and maintainable** as they grow. The right question is rarely *"which framework is better?"* but rather: > What level of structure does your organisation need right now, and how will that change over time? Our experience consistently shows that most development teams benefit from the clear structural guidance a framework provides and D'fflib, in particular, **reduces ambiguity**, **accelerates onboarding**, and **prevents the architectural drift** that makes codebases expensive to change over time. In our honest (and likely subjective) opinion, it remains the **recommended choice for enterprise-grade Salesforce development**. Nevertheless, the choice is ultimately yours to make based on what serves your team best. --- # EDP & fflib URL: /dfflib/docs/what/fflib-enterprise-design-patterns/ Explaining the foundations of our D'fflib framework: Enterprise Design Patterns and fflib. This article shares the roots of the D'fflib framework, their intents and application. As D'fflib wouldn't exist without the original `fflib` (`apex-common`) coding framework, which is a **theoretical application of the Apex Enterprise Design Patterns**, putting **Separation of Concerns** and **Single Responsibility Principles** into practice. D'fflib takes that to the next level, continuing to apply ground principles and best-practices, while elevating the theoretical framework **to a developer enabling framework**. Understanding the intent and reasoning behind a framework is what allows you to fully leverage its benefits and apply it correctly. This article covers the roots of D'fflib, starting with the core principles and patterns, followed by the framework itself. ## Coding Principles & Best-practices [#coding-principles--best-practices] Most developers have encountered code so complex and intertwined that it took hours to digest, let alone fix a bug or extend for a new feature. You'd rather drop the whole functionality and start over. Most have also been in situations where it took many iterations to get a feature working, leaving little time to clean up. "We'll do that later, or create a technical debt story..." might be a familiar phrase. Since both scenarios are very likely to occur in coding environments, it's crucial to have core principles and best practices which can guide us during development, reducing overhead of 'cleaning up', and also reducing overhead for future maintenance. Such guidance might slow down development upon adoption, but when fully embraced it will save a significant amount of time in both initial and future development. Proper coding guidelines and standards can help to make code: * Easier to maintain (read and scan, and less duplicate/scattered code); * Easier to scale (reuse and extend); * Easier to onboard new developers (understand and debug); * Easier to test (unit and regression testing); * Faster go-to-market (less overhead in delivery and maintenance and shorter test runtimes) While this may seem to apply only to large-scale enterprise applications, it's worth considering the same for personal single-person projects: how well would you understand your own code a year from now, after many other projects have drawn your attention in between? Applying these principles in any codebase pays off in the long run, especially once they become part of your standard delivery practice and the initial adoption overhead becomes negligible. Two guiding principles which are used across many programming languages and frameworks are the Single Responsibility Principle and Separation of Concerns: ### Single Responsibility Principle (SRP) [#single-responsibility-principle-srp] **How to set up your code**: A software design principle stating that each class or module should have only one responsibility or job to do. In other words, the method or class should have only one reason to change. This principle helps to make code more maintainable and easier to understand, as it reduces the complexity of the code and makes it easier to identify where changes need to be made when requirements change. When code starts to grow and more functionality is requested, which can't be fit within that responsibility, it should be isolated and moved to a new method/class. This also implies that when properly applying SRP in (unit) tests, tests would only test the sole responsibility of the method or class, and thus ignore/mimic/skip/mock functionality from other methods or classes. This way it will only test the method/class itself and not the full chain. Resulting in the ability to, among other things, simplify what test data is truly needed for the responsibility of that method/class. Avoiding the need to insert all kinds of Account related data, to allow testing an Opportunity Trigger (and causing confusion for future maintenance or new developers joining the project). ### Separation of Concerns (SoC) [#separation-of-concerns-soc] **Where to put your code**: A software design principle for separating the code base into distinct layers, each addressing a separate concern. Like the [Model-View-Controller](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) setup for website development, [Hexagonal Architecture](https://en.wikipedia.org/wiki/Hexagonal_architecture_\(software\)) or usage of UI states ([Flux](https://blog.mgechev.com/2015/05/15/flux-in-depth-overview-components/) / [Redux](https://en.wikipedia.org/wiki/Redux_\(software\))) in frontend development. Each layer has its own responsibility and should adhere to it, simplifying readability and maintainability of the code and separating the concerns. Typical layers are: Presentation, Business Logic, Data Access and Database layers. Every developer is then able to (more) easily determine the proper place to debug or extend existing functionality. Reducing onboarding time for new developers, encouraging reuse and avoiding duplication of code (DRY - Don't Repeat Yourself) or time spent on similar functionality. *** ## (Apex) Enterprise Design Patterns (EDP) [#apex-enterprise-design-patterns-edp] In Martin Fowler's book "[Patterns of Enterprise Application Architecture](https://martinfowler.com/books/eaa.html)" (2002) a collection of design patterns for building enterprise applications was published which are still used in modern frameworks like Spring (Java), Entity Framework (.NET), Django (Python) and also fflib (Apex), proving the timeless value and language-agnostic nature of Fowler's patterns for enterprise software architecture. In context of Salesforce and Apex development, the most relevant patterns are related to unique characteristics of the Salesforce platform, such as governor limits, bulkification requirements and the need for efficient data access and manipulation. * Complex business logic that evolves over time * Concurrent access by multiple users * Data persistence across relational databases * Integration with other systems * Presentation across multiple interfaces This is where the Apex Enterprise Design Patterns come into play, prescribing how to structure code and ensure each method has one purpose (decoupled) and is reusable; while applying best practices: * **Domain Pattern**: Encapsulates business logic and rules related to specific SObjects, ensuring that logic is centralised and reusable. * **Selector/Repository Pattern**: Encapsulates SOQL queries and data retrieval logic, promoting reuse and bulkification, while being SObject specific. * **Service Pattern**: Orchestrates business operations and interactions across multiple SObjects (domain and selector layers) and the database. * **Unit of Work Pattern**: Manages and batches DML operations to optimise performance and ensure data integrity, while reducing the risk of exceeding governor limits and auto-applying transaction controls for security, rollbacks and error handling. These patterns described by Martin Fowler thus help to structure your code in a way that promotes maintainability, scalability, and testability, while also adhering to the characteristics, benefits and challenges of the Salesforce platform. *** ## FFLib [#fflib] FFLib is an open‑source, opinionated implementation/toolkit that codifies Enterprise Design Patterns (EDP) into concrete base classes, interfaces and utilities. It originates from *"Financial Force Library"*, since it was originally developed by the company FinancialForce (now [Certinia](https://en.wikipedia.org/wiki/Certinia)). Their CTO (Andrew Fawcett) liked it so much that he decided to share this with the world, leading to their initial publication at [Dreamforce 2013](https://docs.google.com/file/d/0B6brfGow3cD8RVVYc1dCX2s0S1E) and the current open-source repositories ([fflib-apex-common](https://github.com/apex-enterprise-patterns/fflib-apex-common) and [fflib-apex-mocks](https://github.com/apex-enterprise-patterns/fflib-apex-mocks)). The library provides the foundation for adopting, implementing and extending the EDPs through a set of base classes and interfaces. Additionally, the `apex-mocks` repository provides a framework to stub ('fake response') and mock ('verify interaction') methods in unit tests to help other projects to follow these coding best practices and gain the benefits of maintainability, scalability and testability, while chopping off a significant amount of unit test runtime. Over time FFLib has been widely adopted across the Salesforce ecosystem (500+ forks and \~1k stars) and has been fully acknowledged and embraced by Salesforce as best-practices for Apex development, including [dedicated Trailheads](https://trailhead.salesforce.com/users/rvandenassum/trailmixes/apex-enterprise-design-patterns). It is credit to the Apex Enterprise Patterns Core team that they've enabled and simplified the proper application of these patterns within the Salesforce ecosystem. Curious for some code examples of how to implement the different layers and patterns? Click here. D'fflib is an extension pack to truly enable developers, while leveraging the proven fflib framework. Curious to see what this entails and how you or your team might benefit? ### The layers and definitions [#the-layers-and-definitions] FFLib provides base classes and interfaces which can be extended when implementing a class for a specific layer. Allowing guidance to implement EDP and with that shaping a clear code structure applying Separation of Concerns. Despite the guidance, it is not mandatory to have all code structured in this way, allowing a phased adoption. However, the true benefit comes when a large portion of the code base is structured in the prescribed way. | EDP | Purpose / Relevancy | How implemented with FFLib | | :--------------------------------- | :------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------- | | Domain layer | SObject specific class for reusable business logic like trigger handlers | `class DOM_Accounts extends fflib_SObjectDomain`
[→ see how to implement](/dfflib/docs/how/domains) | | Selector / Repository | SObject specific class to centralise data retrieval (soql queries) | `class SEL_Accounts extends fflib_SObjectSelector`
[→ see how to implement](/dfflib/docs/how/selectors) | | Service / Application layer | Orchestrator class for cross-SObject business logic classes | `class SRV_OpportunityRenewal`
[→ see how to implement](/dfflib/docs/how/services) | | Unit of Work | Gathers and executes DML operations centralising transaction management | `uow.registerNew( newAccount );`
`uow.commitWork();`
[→ see how to implement](/dfflib/docs/how/unit-of-work) | | Dependency Injection & Testability | Automatically applied due to framework interfaces and factories, enabling mocking and stubbing of layers | `fflib_ApexMocks mocks = new fflib_ApexMocks();`
[→ see how to implement](/dfflib/docs/how/testing-mocking) | For a full overview of the exact layers and their interactions, [→ check the Layer overview page](/dfflib/docs/how/overview). --- # D'fflib URL: /dfflib/docs/what/dfflib/ Elaborating on the origin, reasoning and purpose of D'fflib. D'fflib focuses on enabling developers by simplifying their fflib-interactions through shortcuts and significantly extending the framework and improving performance. D'fflib is an extension of fflib/Apex Design Patterns with some significant enrichments to further **unlock developer efficiency**. Where the fflib framework focuses on providing a solid foundation for building scalable and maintainable Salesforce applications, D'fflib takes this a step further from technical implementation to an efficiency gaining developer experience. ## Origin [#origin] Deloitte adopted fflib in 2016 across multiple projects, each applying desired adjustments and enrichments (like metadata driven setup, SOQL function support, Unit of Work support for approval processes and emails etc). In 2019 we started to consolidate these versions into one centralised version for existing and new projects, and even further expanding it to fit our needs and help developers in their delivery (in the era before AI). Especially when rolling this standard to our Global Delivery Centres, we experienced the need to simplify the framework to enable scalability, and the need to implement from a developer efficiency perspective. We've decided to open-source our version for multiple reasons, as can be [read here](/dfflib/docs/why/dfflib-open-source), but mostly to contribute back to the community and spark some interest and inspiration to further unlock efficiency. ## Extensions [#extensions] Aside from the smaller enrichments, like updating to the latest API version, correcting minor bugs and comment typos, there are five main areas of extension: Due to internal dependencies, those can't be shipped independently yet (see [FAQ response](/dfflib/docs/faq#installation-why-not-modular)), but we've structured the code to be fit-for-future and allow ability to untangle for specific projects. *Click on a feature card below for more details* ### Provided as package with utils [#provided-as-package-with-utils] * Lightning-fast install and updates via (unlocked) package links * Optionally including latest `fflib-apex-common` and `fflib-apex-mocks` to reduce maintenance overhead * Mitigating project dependencies by migrating the tests to rarely used SObjects (`ContactRequest` and `Solution` only in `dfflib_DatabaseTest`) * Eliminating need for 78 classes in project repository * Cutting-off \~5 minutes from All Test runtime, as those only run on package install * Providing ready-to-use (and unit-test-covered) accelerators * Reducing repetitive code, speed up development and encourage consistency * Including input validations, collection processing and Exception types * `defineMock()` to standardise mock definitions and eliminate 2 lines for each selector/service mock. *[→ see GitHub Release Notes](https://github.com/deloitte-engineering/dfflib-code/releases) for latest package links.* ### Database [#database] * Introducing standardised patterns for both Selectors and Unit of Work * Introducing `dfflib_Database.Context` to control (System/User) Modes * Enabling control for calling class to specify Context (thus Sharing & Security) upon initiation (!) * Eliminating need for repetitive `WithoutSharing` inner-selector-classes, or custom `IDML` definitions * Proper separation of concerns, allowing you to increase overall test coverage Full redesign of Unit of Work * Supporting latest DML operations (such as Priority, Immediate, SaveResults, Advanced Relationships, Approvals, Emails and Events) * Realising 14x faster Unit of Work cycle times (only initiating requested maps, eliminating `getDescribe` and String casts) * Enable `registerUpsert` for multiple fields per SObject * Increasing Unit of Work test coverage to 98% to guarantee deployment stability * Squashing nasty bugs and increasing coverage on project-independent SObjects * Unlocking proper selector unit tests AND eliminating CPU costs of performing query during unit test * Supporting latest query related `Database`-methods: Cursor, Query, QueryLocator. With and without binds * Supporting latest SOQL functions and clauses (like `DISTANCE`, `FOR` and `GROUP BY`) * Supporting full aggregate result, including the ability to mock in unit tests * Enabling simplified unit test assertions by predefined common validations * Performance improvement by eliminating `SObjectDescribe` for each selector-field ### Domain & Triggers [#domain--triggers] * Integrating light-weight Trigger Handler Framework in `dfflib_SObjectDomain` * Enabling optimised, scalable and bulkified trigger handlers (with `initialize()`, `process()` and `finalize()` abstract methods) * Enabling consistency and clarity on what logic is run when ### Metadata driven [#metadata-driven] * Moving all fflib mappings from central class to metadata * Enabling SFDX packaging * Auto-including Application class to quickstart developers * Reducing code conflicts in projects with multiple developers/teams ### Test Data Framework [#test-data-framework] * Adding Test Data Builder framework to simplify creation for local and inserted test data * Speeding up unit test creation by centralising test data construction and default values * Enabling formula and read-only field population without DML via JSON serialisation ### Smaller Enrichments [#smaller-enrichments] * Added Unit of Work registration validation to prevent invalid combinations * Increased test coverage (82% > 94%) and decreased unit test runtime * Made framework fully sf code-analyzer (`PMD`) compliant * Running on latest API version * Leveraging latest features like `??` (null coalescing operator) or new `System.Assert` class ### Contributions to fflib repositories [#contributions-to-fflib-repositories] * Introduction of 9 new `fflib_SObjects` utility methods, hygiene and performance improvements ([#536](https://github.com/apex-enterprise-patterns/fflib-apex-common/pull/536)) * `fflib_SObjectDescribe` performance optimisations ([#539](https://github.com/apex-enterprise-patterns/fflib-apex-common/pull/539)) * Simplified `setMocks` to avoid issue of missed `SObjectType()` stub ([#453](https://github.com/apex-enterprise-patterns/fflib-apex-common/pull/453)) * Correction for `registerDirty` to only register dirty-fields when specified ([#201](https://github.com/apex-enterprise-patterns/fflib-apex-common/pull/201)) --- # Accelerators & Utilities URL: /dfflib/docs/what/accelerators-utilities/ Our ambition is to reduce code repetitions and ease the life of developers, therefore a proper set of utilities and accelerating methods and defaults couldn't be missed. D'fflib comes with a set of ready-to-use utilities and accelerators to speed up your Apex development. Below is the list of method signatures with a brief description of their purpose, per base-class. ## dfflib_Application [#dfflib_application] ### Simplified & standardised mocks [#simplified--standardised-mocks] Eliminating multiple lines of (boilerplate) code, making it easier to remember and avoiding failures due to accidentally forgotten lines. A single line per mock, identical for all layers, takes away the concerns of constructing, defining and setting a stubbed/mocked class. Improving readability and helping new-joiners to more easily understand and apply the code. D'fflib defineMock() fflib-apex-common mock setup ```apex fflib_ApexMocks mocks = new fflib_ApexMocks(); dfflib_ISObjectUnitOfWork uowMock = dfflib.unitOfWork.defineMock( mocks ); DOM_Accounts m_domAccounts = ( DOM_Accounts ) dfflib.domain.defineMock( mocks, DOM_Accounts.class, Account.SObjectType ); SEL_Accounts m_selAccounts = ( SEL_Accounts ) dfflib.selector.defineMock( mocks, SEL_Accounts.class, Account.SObjectType ); SRV_Response m_srvResponse = ( SRV_Response ) dfflib.service.defineMock( mocks, SRV_Response.class ); SRV_Response m_srvIResponse = ( SRV_Response ) dfflib.service.defineMock( mocks, SRV_Response.class, SRV_Response.IService.class ); ``` ```apex fflib_ApexMocks mocks = new fflib_ApexMocks(); fflib_ISObjectUnitOfWork uowMock = ( fflib_ISObjectUnitOfWork ) mocks.mock( fflib_ISObjectUnitOfWork.class ); DOM_Accounts m_domAccounts = ( DOM_Accounts ) mocks.mock( DOM_Accounts.class ); SEL_Accounts m_selAccounts = ( SEL_Accounts ) mocks.mock( SEL_Accounts.class ); SRV_Response m_srvResponse = ( SRV_Response ) mocks.mock( SRV_Response.class ); SRV_Response m_srvIResponse = ( SRV_Response ) mocks.mock( SRV_Response.IService.class ); mocks.startStubbing(); mocks.when( m_domAccounts.sObjectType() ).thenReturn( Account.SObjectType ); mocks.when( m_selAccounts.sObjectType() ).thenReturn( Account.SObjectType ); mocks.stopStubbing(); Application.domain.setMock( m_domAccounts ); Application.selector.setMock( m_selAccounts ); Application.service.setMock( SRV_Response.class, m_srvResponse ); Application.service.setMock( SRV_Response.IService.class, m_srvIResponse ); Application.unitOfWork.setMock( uowMock ); ``` ## dfflib_Utils [#dfflib_utils] Given that all proper methods should validate their inputs, and provide a user-friendly error, `dfflib_Utils` provides a set of utility methods and Exception-definitions to facilitate input validation and string population: ### Base Exceptions [#base-exceptions] `dfflib_Utils` provides three ready-to-use Exceptions: ```apex dfflib_Utils.InvalidImplementationException dfflib_Utils.InvalidInputValueException dfflib_Utils.MissingDataException ``` ### Input verifications [#input-verifications] Methods which throw a `dfflib_Utils.InvalidInputValueException` when the verification fails. * **`dfflib_Utils.verifyNotBlank( String param, String paramName );`** * **`dfflib_Utils.verifyNotEmpty( List objList, String paramName );`** * **`dfflib_Utils.verifyNotNull( Object param, String paramName );`** Due to the invariant implementation of Sets in Apex `Set` or `Set` are never an instance of `Set`. As a workaround, one could initiate their own input-specific verify-method, or `dfflib_Utils.verifyNotEmpty( new List( mySet ), 'paramName' );`. Though, be conscious of the additional conversion overhead. ### String construction [#string-construction] * **`dfflib_Utils.message( String message, String substitutionString );`**\ Shortcut to properly inject fields into a String without too many String manipulations. Returning `String.format( message, new List{ substitutionString } );`. ## fflib_SObjects [#fflib_sobjects] D'fflib brings a full set of Collection utilities, which - after alignment with AEP core team - have [been backported](https://github.com/apex-enterprise-patterns/fflib-apex-common/pull/536) to `fflib-apex-common`, to prevent the need for introducing an extension-version for `fflib_SObjects`. These methods are available in any Domain method, since `dfflib_SObjectDomain` extends `fflib_SObjects`. Methods with a `*` are `public` and can also be called outside a Domain, via `new fflib_SObjects( records )`. All others are `protected`: expose them via a Domain business method. ### List utilities [#list-utilities] (Semi-)alphabetical list of utility methods which consume the `records` (`List`) variable via the `getRecords()` method: #### Update field values [#update-field-values] * **`void clearField( Schema.SObjectField field )`**\*\ Clears (nullifies) a single field on all provided records. * **`void clearFields( Set fields )`**\*\ Clears (nullifies) multiple fields on all provided records. * **`void setFieldValue( Schema.SObjectField field, Object value )`**\ Sets the same value on the given field for all provided records. * **`void setFieldValueByMap( Schema.SObjectField fieldToCheck, Schema.SObjectField fieldToUpdate, Map values )`**\ Sets the field value (to update) with the Map-value, sharing the same key as the value in `fieldToCheck`. Records without matching key are untouched. #### Collect values for a specific field (e.g. all Ids, or Statuses) [#collect-values-for-a-specific-field-eg-all-ids-or-statuses] * **`Set getRecordIds()`**\*\ Returns the record Ids of all provided records. * **`Set getFieldValues( Schema.SObjectField field )`**\ Collects and returns a Set of values for the given field across all records. * **`Set getIdFieldValues( Schema.SObjectField field [, Boolean includeNulls] )`**\ Used for fetching Ids from given Id field. By default `null` is added to the result set. * **`Set getParentIdFieldValues( String fieldWithDotRelation )`**\*\ Plucks Ids via a dotted relationship path of any depth (e.g. `'Owner.ContactId'` or `'Parent.Owner.ManagerId'`), excluding null values. Records with an unpopulated intermediate relationship are skipped. * **`Set getStringFieldValues( Schema.SObjectField field [, Boolean includeNulls] )`**\ Used for fetching String values from given field. By default `null` is added to the result set. #### Filter List by field values [#filter-list-by-field-values] * **`List getRecordsByFieldValue( Schema.SObjectField field, Object value )`**\ Returns records where the given field equals the provided value. * **`List getRecordsByFieldValues( Schema.SObjectField field, Set values )`**\ Returns records where the given field matches any value in the provided set. * **`List getRecordsWithAllBlankFieldValues( Set fields )`**\ Returns records where all given fields are blank (null or empty string). * **`List getRecordsWithAllNotBlankFieldValues( Set fields )`**\ Returns records where all given fields are populated. * **`List getRecordsWithBlankFieldValues( Schema.SObjectField field )`**\ Convenience overload to filter records where a single field is blank (null or empty string). * **`List getRecordsWithBlankFieldValues( Set fields )`**\ Returns records where at least one of the given fields is blank. * **`List getRecordsWithNotBlankFieldValues( Schema.SObjectField field )`**\ Convenience overload to filter records where a single field is populated. * **`List getRecordsWithNotBlankFieldValues( Set fields )`**\ Returns records where at least one of the given fields is populated. #### Group List by field values to a Map [#group-list-by-field-values-to-a-map] * **`Map> groupRecordsByFieldValue( Schema.SObjectField identifierField )`**\*\ Method to easily construct a Map from a List of SObjects, with key set by the value of the identifier field. Throws a `fflib_Objects.InvalidValueException` when a record has no value for the given field. ## fflib_SObjectDescribe [#fflib_sobjectdescribe] Similarly to the utility methods in `fflib_SObjects`, D'fflib provides static picklist-utility-methods which can [now also](https://github.com/apex-enterprise-patterns/fflib-apex-common/pull/536) be found in `fflib-apex-common`. ### Picklist related utilities [#picklist-related-utilities] When in need to validate or process picklist values or users' input, you can leverage the out-of-the-box, static, centralised and optimised methods related to SObject definitions. * **`fflib_SObjectDescribe.getPicklistLabels( Schema.SObjectField selectedField )`**\ Returns the labels of a picklist field as a `List`, unmodified. Use `getPicklistValues()` or `isValidPicklistValue()` for API-value comparisons. * **`fflib_SObjectDescribe.getPicklistValues( Schema.SObjectField selectedField )`**\ Returns the `List` (label and value) of a picklist field; returns an empty list for non-picklist fields. * **`fflib_SObjectDescribe.isValidPicklistValue( Schema.SObjectField sObjField, String value )`**\ Returns TRUE when the value is a valid (case-insensitive) picklist API value for the provided field; FALSE for a blank or non-matching value. --- # Database context URL: /dfflib/docs/what/database-context/ D'fflib uses the user mode features from Spring '23 (API 57) to simplify how you control sharing and FLS/CRUD, and to (finally) enable proper unit tests for selectors. D'fflib separates database interactions from Selectors and the Unit of Work, giving developers a much simpler and standardised way to define and control sharing and FLS/CRUD access. It also unlocks the ability to unit test a Selector, improves performance and reduces repetitive code. Spring '23 (API 57) introduced [`WITH USER_MODE`](https://help.salesforce.com/s/articleView?id=release-notes.rn_apex_User_Mode_GA.htm\&release=242\&type=5), [`System.AccessLevel`](https://help.salesforce.com/s/articleView?id=release-notes.rn_apex_User_Mode_GA.htm\&release=242\&type=5) and [`queryWithBinds`](https://help.salesforce.com/s/articleView?id=release-notes.rn_apex_bind_var_soql.htm\&language=en_US\&release=242\&type=5). These made it possible to separate Database concerns from the Unit of Work and Selectors, significantly simplifying sharing and FLS controls, while reducing code volumes. ## Main benefits [#main-benefits] The new database context is fully backward compatible and can be gradually adopted, since each (selector) class can individually be migrated to leverage the (below) benefits: ### Simplified security control [#simplified-security-control] * `dfflib_Database.Context` provides one enum that bundles both Sharing- & Permissions controls in one. Simplifying complexity (especially to junior developers). * Standardised syntax for both Selectors and Unit of Work to specify the desired Security Access Control (Database Context) (see [#2](#calling-class-specifies-running-database-context)). ### Calling class specifies running Database Context [#calling-class-specifies-running-database-context] Each calling class can construct a Selector and/or Unit of Work in the desired Database Context, making methods reusable for different sharing contexts, without the need for customisations in the called-method (see [#6](#reduced-custom-implementations-and-duplicate-code)), while granting full control over sharing- and FLS/CRUD enforcement. ```apex dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( dfflib_Database.Context.INHERIT ); List newLeads = SEL_Leads.newInstance( dfflib_Database.Context.FULL ).getPendingLeads(); ``` ### Proper asserts in selector unit tests [#proper-asserts-in-selector-unit-tests] Originally, one needed to call `Database.query()` directly in a selector. This made it impossible to prevent the query from executing in unit tests, and also required (time-consuming) test data creation to do some proper asserts. Now `System.Database` operations have been moved to the Database Proxy, making it possible to mock, and assert solely the single responsibility of the selector method (see [#6](#reduced-custom-implementations-and-duplicate-code)). Thus, this not only enables proper assertions, but also improves performance by eliminating the query and the need for test data creation. Shortcuts have been introduced to simplify selector unit test verifications. Both to simplify adoption for fresher developers, avoid forgetting the boilerplate, and simply to reduce code lines. *→ Click to read more.* ### Improved separation of concerns [#improved-separation-of-concerns] We've untangled some responsibility ambiguity, giving each class a single and clear responsibility. * `dfflib_SObjectUnitOfWork` - record registration and memoisation; * `dfflib_QueryFactory` - query string construction; * `dfflib_SObjectSelector` - security control and calling QueryFactory; * `dfflib_Database_DMLProxy` - actual database interactions via `System.Database`. ### Performance benefits by eliminating `getFieldPath()` [#performance-benefits-by-eliminating-getfieldpath] Originally in fflib, when enforcing FLS (Field Level Security), logic would gather `DescribeFieldResult` for each field in the QueryFactory to call `.isAccessible()`. With the introduction of `WITH USER_MODE` this validation is moved to optimised Salesforce backend, resulting in quite some performance benefit upon query execution and also eliminating custom regex to allow casts and other SOQL functions to pass `getFieldPath()`. ### Reduced custom implementations and duplicate code [#reduced-custom-implementations-and-duplicate-code] * Deprecation of custom `IDML` implementations for Unit of Work, as all different flavours are now pre-defined in `dfflib_Database_DMLProxy`. * No need for `without sharing` inner classes in selectors to bypass sharing context. ### Faster and project independent `fflib` unit tests [#faster-and-project-independent-fflib-unit-tests] Originally, the Unit of Work had to assert all complex scenarios, like relational insertions, requiring more complex test data constructions (like Opportunities with Line Items). Due to the separation of concerns UoW only needs to assert the registrations, since the Database Proxy is mocked. The Proxy in turn only needs to insert the 'simple' `Database.insert()` methods, resulting in: * Faster unit tests, as `isParallel = true` is unlocked when less test data is created. * Ability to move to simpler SObjectType (`ContactRequest` and `Solution`) in unit tests, as e.g. relations don't need to be tested in the database. Reducing test-failures due to project specific required fields or validations. * Cleaner and fewer unit test methods, due to untangled logic. ## How it works [#how-it-works] ### Database Context enum [#database-context-enum] The `dfflib_Database.Context` enum provides four options which can be specified for record/event manipulations (DML operations) and the retrieval of records (SOQL queries) to specify the desired running security context. | Option | Sharing | FLS/CRUD | AccessLevel | Examples | | -------------------------- | :---------------: | :---------: | :-----------: | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `FULL` | `with sharing` | | `USER_MODE` | | | `SHARING_SKIP_PERMISSIONS` | `with sharing` | | `SYSTEM_MODE` | | | `NONE` | `without sharing` | | `SYSTEM_MODE` | | | `INHERIT` | `inherit sharing` | | `SYSTEM_MODE` | | No enum is introduced to enforce FLS/CRUD while relaxing sharing as we believe this is a rare use-case which conflicts with the best-practice of minimal record access. Additionally, this would add a dependency from the new `dfflib_Database.Context` structure to the legacy `enforce`-Booleans. If you need to run a selector `without sharing`, while enforcing FLS and CRUD, this can be achieved by constructing `dfflib_Database.Context.NONE` while setting `enforceFLS` and `enforceCRUD` to `TRUE` using the legacy `newQueryFactory` (see [Selector 2.0](/dfflib/docs/what/selectors)). This still eliminates the need for an inner-class (boilerplate code), while supporting existing requirements/implementations. ### High-level setup [#high-level-setup] To gather a better understanding of the new Database Context functionality, here's a high-level overview of the involved classes and their responsibilities. 1. Introduction of Proxy classes for Database operations * `dfflib_Database_DMLProxy` and `dfflib_Database_QueryProxy`\ Centralising all DML and SOQL operations for the different '*sharing*' flavours (`with`, `without` and `inherit`) and modes (`USER_MODE`, `SYSTEM_MODE`). Thus, listing all `Database` methods wrapped in specific classes, like the original `IDML`. 2. Introduction of `dfflib_Database` class * As (internal) access point to the Proxy classes. * Centralising database security modes to be used for setting sharing context and enforcement of CRUD/FLS on the respective interface implementation. * Deliberate shorter class name given the frequent references (e.g. `dfflib_Database.Context.FULL`). 3. Introduction of `dfflib_Database.Context` enums * Defining the security context within the proxy interface and (independently!) controlling both sharing rules' context, and FLS/CRUD permission level 4. Updated `dfflib_Application` factory `newInstance()` methods to accept a `dfflib_Database.Context` parameter 5. Introduction of `executeQuery` methods in selectors (see [Selectors 2.0](/dfflib/docs/what/selectors)). 6. Introduction of `SelectorVerificationResults` and `mockExecuteQuery` methods for simplified selector unit test validations. ### Technical storyline/background [#technical-storylinebackground] It took quite some effort to get this functionality scalable and for those who're interested, this was because of the following: * Challenge to find a proper SObjectType which is available in all standard Salesforce instances. * [`Individual`](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_individual.htm) is only available when "Data Protection and Privacy" is enabled, which has become default disabled in newer environments. * `ContactRequest`, `EmailMessage`, `Image`, `Macro`, `QuickText`, and `ScoreCare` were considered, but by default Salesforce grants FLS, preventing FLS test methods. * When Shield encrypts the `Name` field of an object, this can't be sorted in a query and should thus be excluded in selector unit tests. * Changing Salesforce behaviours for stable unit tests * Per API 61 (Summer '24) `EventBus.publish()` throws a `System.UnexpectedException` when trying to publish an SObject instead of an Event. --- # Metadata driven URL: /dfflib/docs/what/metadata-driven/ D'fflib is fully metadata-driven, meaning all layer definitions and configurations are stored in metadata files. Originally these definitions/mappings were hardcoded in Apex classes, which increased the risk for conflicts. Upon install, D'fflib is fully metadata-driven, eliminating the risks of code conflicts and enabling the ability to structure your metadata in packages/folders. An [anonymous apex script](/dfflib/docs/how/get-started#migrate-remove-fflib-classes-metadata-creation) is provided to ease the migration. ## Metadata-driven benefits [#metadata-driven-benefits] ### Packaging enabled [#packaging-enabled] Layer definitions can be organised in their corresponding package, making it possible to untangle your codebase into manageable and independent packages. ### Auto-inclusion of Application class [#auto-inclusion-of-application-class] Quite often we heard teams struggle with `apex-common`-install due to ambiguity on the need to manually create an Application class (see [below](#application-classes-compared)). Being metadata-driven, there is no need for projects to create and maintain the class, allowing the `dfflib.cls` to be auto-included upon install and ready to read from metadata. ### Reduced conflicts [#reduced-conflicts] Due to elimination of the central Application class, there is a significant reduction of deployment conflicts and undesired rollbacks of other developers' changes during merges, as each developer will simply create a separate metadata-record instead of modifying the same class upon introduction of new classes. ### Reduced dependency-compilation-errors [#reduced-dependency-compilation-errors] One compilation failure could break a large portion of your code base due to the compilation-dependency chain, as well as a longer compile-time. Moving to metadata eliminates these direct class dependencies via the central Application class. Over time we've come across many project-specific metadata-driven implementations. One clear distinction and lesson learned is to only process the requested metadata records and SObjectTypes, to avoid metadata-compilation errors when e.g. a user has no access to an object like Knowledge, or when specific objects became unavailable due to licence toggling (like Shield or FieldService). D'fflib only retrieves and constructs the SObjectTypes at hand, preventing full-org compilation errors. ### Configuration flexibility [#configuration-flexibility] While not recommended, configurations can be changed without code changes, like the SObject Type sequence in Unit of Work, or the implementation and enablement of layers. ## Application classes compared [#application-classes-compared] Below is a comparison between the new metadata-driven `dfflib` class, which is automatically included upon D'fflib install, and an original Application class, which had to be manually created for the original `apex-common` to define the layer definitions and implementations. D'fflib Application class fflib-apex-common Application class ```apex public with sharing class dfflib{ public static final dfflib_Application.UnitOfWorkFactory unitOfWork = new dfflib_Application.UnitOfWorkFactory(); public static final dfflib_Application.SelectorFactory selector = new dfflib_Application.SelectorFactory(); public static final dfflib_Application.DomainFactory domain = new dfflib_Application.DomainFactory( selector ); public static final dfflib_Application.ServiceFactory service = new dfflib_Application.ServiceFactory(); } ``` ```apex public class Application{ // Configure and create the UnitOfWorkFactory for this Application public static final fflib_Application.UnitOfWorkFactory UnitOfWork = new fflib_Application.UnitOfWorkFactory( new List{ Account.SObjectType, Opportunity.SObjectType, Product2.SObjectType, PricebookEntry.SObjectType, OpportunityLineItem.SObjectType } ); // Configure and create the ServiceFactory for this Application public static final fflib_Application.ServiceFactory Service = new fflib_Application.ServiceFactory( new Map{ IAccountsService.class => AccountsService.class, } ); // Configure and create the SelectorFactory for this Application public static final fflib_Application.SelectorFactory Selector = new fflib_Application.SelectorFactory( new Map{ Account.SObjectType => AccountsSelector.class, Opportunity.SObjectType => OpportunitiesSelector.class, User.sObjectType => UsersSelector.class } ); // Configure and create the DomainFactory for this Application public static final fflib_Application.DomainFactory Domain = new fflib_Application.DomainFactory( Application.Selector, new Map{ Account.SObjectType => Accounts.Constructor.class, Opportunity.SObjectType => Opportunities.Constructor.class } ); } ``` Note the slight change in variable names, correcting from pascal to camel case. ## Metadata types [#metadata-types] D'fflib brings five metadata types to define the layer implementations and configurations. *Click on the cards below to read more about the related layer.* Defines the sequence of SObjects for each Unit of Work operation (to control `Account` is inserted before/deleted after `Contract` to ensure existence). Defines which class implements a specific Service interface, or a non-interface-based Service. Defines which class implements the selector layer for a specific SObject. Defines which class implements the domain layer for a specific SObject. Ability to define a JSON string for `ContactRequest` and `Solution` SObjects, enabling you to pass unit tests in case of project-specific required fields and/or validations. We're currently finalising the migration for Trigger Handler registrations from Domain class to metadata, further enabling packaging, but also a standardised trigger handler disablement via metadata. ## Frequently asked questions [#frequently-asked-questions] This is fully described in our [migration guide](/dfflib/docs/how/get-started#migrate-metadata-creation-script), including an Anonymous Apex script which enables metadata record creation based on the existing Application class. This isn't possible (yet). At initiation the metadata selection is solely based on SObjectType. Hence, the SObjectType fields have been made unique in metadata, so only one metadata record per SObjectType can exist for Domains and one for Selectors, regardless of the package it is stored in. We've considered refactoring, but in our view that would impact backward compatibility for how Domains and Selectors are initiated. Of course we'd love to hear your thoughts and challenges on this as we do think this is (one of the) next steps for D'fflib: allowing package-specific implementation for SObject specific layers. This is mostly dependent on your projects' package structure. Most of our projects have around 80% of the SObject specific layers (Domain, Selector) stored in the business-process-specific packages. The remaining cross-package layers are either moved to a central/core package or kept in the 'remaining' (unpackaged) `force-app` folder. --- # Unit of Work 2.0 URL: /dfflib/docs/what/unit-of-work/ Being 14x faster than the original construct, the Unit of Work 2.0 fully focuses on relaxing developers from any DML related activity. In our perspective the essence of the Unit of Work is to centralise and aggregate DML operations, ensure proper (error) transaction management - without duplicate and scattered try-catches and rollbacks - and simplify and improve readability of complex relationship-registrations. In line with this purpose, we've redesigned the UoW to strengthen these benefits while significantly improving performance and relaxing developers in all their DML related activities. A step-by-step introduction on how to leverage and master the Unit of Work, with concrete example snippets to get started. Have a look yourself on `dfflib_SObjectUnitOfWork` in our repo to explore the code, methods and comments. ## Main enrichments to the Unit of Work [#main-enrichments-to-the-unit-of-work] ### Support for most DML operations, DMLOptions & SaveResults [#support-for-most-dml-operations-dmloptions--saveresults] Most `Database` methods are now supported, eliminating the need for custom `IDoWork` classes. Simplifying not only the usage and mocking, but also improving readability. See full list of supported DML operations [below](#full-methods-list), including a.o. Priority, Immediate, Advanced Relationships, Approvals, Emails and (Standard) Events. Additionally, SaveResults are (optionally) available for when a developer needs to set `DMLOptions` or `AllOrNone = false`. ### Full Database Context support [#full-database-context-support] See the [Database Context](/dfflib/docs/what/database-context) article for standardised way to achieve full access control (sharing and permissions). Our structure eliminates the need for project-specific overrides and 'awareness' of `IDML` outside of Unit of Work. ### 14x faster Unit of Work cycle times [#14x-faster-unit-of-work-cycle-times] Redesign of `Map`-initiations and numerous other optimisations resulted in a significant performance improvement. Across multiple projects we've benchmarked >14x faster operations . ### Improved relationship registrations [#improved-relationship-registrations] * Relationships can be registered per DML Operation to prevent resolving relations too soon. * A record instance can be registered as both new and dirty within the same Unit of Work. * Added validation to ensure all relationships are 'executed' (e.g. register relationship, but not the child record). ### Deprecation of `on...`-events [#deprecation-of-on-events] In our perspective these methods only caused overhead and complexity, while we never needed these in any project and believe they are in conflict with the modularity principle where one doesn't need to know how a called method performs. ### Minor tweaks and fixes [#minor-tweaks-and-fixes] * Increased test coverage (68% > 98%) after migrating to project-independent SObjectTypes. * Added registration validations to prevent invalid combinations (e.g. publishing a non-Event). * Allowing reuse of the same UoW instance, by resetting the work after `commitWork()`. * Squashed nasty bugs, like `registerDirty` overriding previous registrations of the same record when no `dirtyFields` are provided. ## Full methods list [#full-methods-list] Below is the full method comparison between `apex-common` and D'fflib's `dfflib_ISObjectUnitOfWork`, indicating the differences and similarities.
Method signature apex-common D'fflib
commitWork()
hasWork()
### Constructors [#constructors]
  • dfflib_SObjectUnitOfWork()
  • dfflib_SObjectUnitOfWork(List sObjTypes)
  • dfflib_SObjectUnitOfWork(List sObjTypes, fflib_SObjectUnitOfWork.IDML dml)
  • dfflib_SObjectUnitOfWork(dfflib_Database.Context)
  • dfflib_SObjectUnitOfWork(List sObjTypes, dfflib_Database.Context)












setContext(dfflib_Database.Context)
### Register New/Insert [#register-newinsert]
  • registerNew(SObject)
  • registerNew(List)
  • registerNew(SObject, Schema.SObjectField, SObject)
  • registerNewDmlOptions(Schema.SObjectType, Database.DMLOptions)
  • registerNewAllOrNone(Schema.SObjectType, Boolean)












### Register Dirty/Update [#register-dirtyupdate]
  • registerDirty(SObject)
  • registerDirty(List)
  • registerDirty(SObject, Schema.SObjectField, SObject)
  • registerDirty(SObject, List)
  • registerDirty(SObject, List, Schema.SObjectField, SObject)
  • registerDirty(List, List)
  • registerDirtyDmlOptions(Schema.SObjectType, Database.DMLOptions)
  • registerDirtyAllOrNone(Schema.SObjectType, Boolean)


















### Register Upsert (deprecated) [#register-upsert-deprecated]
  • registerUpsert(SObject)
  • registerUpsert(List)
### Register Upsert [#register-upsert]
  • registerUpsert(SObject, Schema.SObjectField externalIdField )
  • registerUpsert(List, Schema.SObjectField externalIdField )
  • registerUpsert( SObject record, SObjectField externalIdField, SObjectField relatedToParentField, SObject relatedToParentRecord )
  • registerUpsertedAllOrNone(Schema.SObjectType, Boolean)










### Register Delete/Recyclebin [#register-deleterecyclebin]
  • registerDeleted(SObject)
  • registerDeleted(List)
  • registerEmptyRecycleBin(SObject)
  • registerEmptyRecycleBin(List)
  • registerPermanentlyDeleted(SObject)
  • registerPermanentlyDeleted(List)
  • registerDeletedAllOrNone(Schema.SObjectType, Boolean)
















### Register Undelete [#register-undelete]
  • registerUndeleted(SObject)
  • registerUndeleted(List)
  • registerUndeletedAllOrNone(Schema.SObjectType, Boolean)
### Register Custom Platform Event (`AsyncProcess__e`) [#register-custom-platform-event-asyncprocess__e] ### Register Standard Platform Event (`BatchApexErrorEvent`) [#register-standard-platform-event-batchapexerrorevent]
  • registerPublishAfterFailureTransaction(SObject)
  • registerPublishAfterFailureTransaction(List)
  • registerPublishAfterSuccessTransaction(SObject)
  • registerPublishAfterSuccessTransaction(List)
  • registerPublishBeforeTransaction(SObject)
  • registerPublishBeforeTransaction(List)


### Register Work [#register-work]
  • registerWork(dfflib_SObjectUnitOfWork.IDoWork)
### Register Relationships [#register-relationships]
  • registerRelationship(SObject, Schema.SObjectField, SObject)
  • registerRelationship(SObject, Schema.SObjectField, SObject, dfflib_SObjectUnitOfWork.DMLActions)
  • registerRelationship(SObject, Schema.SObjectField, Schema.SObjectField, Object)
  • registerRelationship(SObject, Schema.SObjectField, Schema.SObjectField, Object, dfflib_SObjectUnitOfWork.DMLActions)
  • registerRelationship(Messaging.SingleEmailMessage, SObject)
  • registerRelationship(Approval.ProcessRequest, SObject)














### Register Approval Process [#register-approval-process]
  • registerApprovalProcess(Approval.ProcessRequest)
  • registerApprovalProcess(Approval.ProcessRequest, SObject)
### Register Email [#register-email]
  • registerEmail(Messaging.Email)
  • registerEmail(Messaging.SingleEmailMessage, SObject)




### Register Immediate [#register-immediate]
  • registerDeletedImmediate(SObject)
  • registerDeletedImmediate(List)
  • registerDirtyImmediate(SObject)
  • registerDirtyImmediate(List)
  • registerNewImmediate(SObject)
  • registerNewImmediate(List)
### Register Priority [#register-priority] ( [example](/dfflib/docs/how/unit-of-work#priority-) )
  • registerPriorityDeleted(SObject)
  • registerPriorityDeleted(List)
  • registerPriorityDirty(SObject)
  • registerPriorityDirty(List)
  • registerPriorityDirty(SObject, Schema.SObjectField, SObject)
  • registerPriorityNew(SObject)
  • registerPriorityNew(List)
  • registerPriorityNew(SObject, Schema.SObjectField, SObject)
  • registerPriorityUpsert(SObject, Schema.SObjectField externalIdField)
  • registerPriorityUpsert(List, Schema.SObjectField externalIdField)
### SaveResults [#saveresults] ( [example](/dfflib/docs/how/unit-of-work#saveresults-) )
  • setSaveResultsRequired(Boolean)
  • getApprovalProcessResults()
  • getDeletedResults(Schema.SObjectType)
  • getDirtyResults(Schema.SObjectType)
  • getEmailResults()
  • getEmptyRecycleBinResults(Schema.SObjectType)
  • getNewResults(Schema.SObjectType)
  • getPublishResults(Schema.SObjectType)
  • getUndeletedResults(Schema.SObjectType)
  • getUpsertResults(Schema.SObjectType)
### Reset Unit of Work [#reset-unit-of-work]
  • resetSaveResults()
  • resetWork()
--- # Selectors 2.0 URL: /dfflib/docs/what/selectors/ Providing full SOQL support, while unlocking proper unit test methods for the selector layer. D'fflib enables security/sharing-agnostic methods by enabling calling classes to define the `Database Context`. This unlocks proper test assertions, while preventing query-calls and comes with a full set of supporting methods to reduce complexity and repetitive code. Additionally, there is now full support for `AggregateResults`, `Cursor` and SOQL functions like `DISTANCE` and `TYPEOF`. Each selector can be upgraded individually, allowing a gradual adoption. Selectors have the single responsibility to fetch the desired SObject records from the database, while respecting security and sharing settings. D'fflib aims to enable developers to apply best-practices (like proper unit tests and asserts), while reducing the number of code lines and complexity needed to achieve this. Most Selector enrichments are a consequence of the Database Context and Proxy. *→ Click to read more about the implementation, reasoning and benefits.* *→ Click to read more about how to write selectors with D'fflib, including examples of new features.* ## Main enrichments to the Selectors and QueryFactory [#main-enrichments-to-the-selectors-and-queryfactory] All enrichments are elaborated with code examples below. ### Simplified application of security management, making methods automatically reusable for different Contexts [#simplified-application-of-security-management-making-methods-automatically-reusable-for-different-contexts] To deviate sharing (`without` or `inherit`) for a selector method in `fflib`, one had to create a `without sharing` annotated inner class and optionally introduce a `withSharing` Boolean input parameter to allow method reuse for different sharing contexts (see snippet below). D'fflib simplifies this by allowing you to construct a Selector instance in a specific Database Context, implying: * Methods become agnostic for Database Contexts, enabling reuse and making context specific logic redundant; * `enforceFLS`/`enforceCRUD` are replaced by `Context` (like `FLSEnforcement` and `DataAccess` before), reducing the number of Booleans for `newQueryFactory( true )` ### Proper test assertions and support [#proper-test-assertions-and-support] For this simplification ([#1](#simplified-application-of-security-management-making-methods-automatically-reusable-for-different-contexts)), the responsibility of calling `Database`-query-methods shifted to the Query Proxy class, as no `Database.query` is called anymore in a selector method. This means all Database methods can now be mocked/avoided during unit test runtime. Additionally, to centralise and eliminate repetitive boilerplate code D'fflib comes with [built-in unit test methods](#unit-test-validations), automatically mocking the Proxy class to prevent query-execution and providing simple verification methods. For unit tests of classes calling selector methods, [`defineMock()`](/dfflib/docs/what/accelerators-utilities#simplified--standardised-mocks) was introduced to centralise layer-mocking, but also significantly reduce boilerplate code and prevent unexpected behaviour when not mocking the `sObjectType()` selector class method. ### Full Aggregate Results support (construction and mocking) [#full-aggregate-results-support-construction-and-mocking] D'fflib fully supports: * The construction of queries with SOQL functions like `AVG`, `SUM`, `COUNT`, `MIN` and `MAX` (also in legacy form with `enforceFLS` and `getFieldPath()`) * Applying a [`HAVING`](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_having.htm) condition to filter `GROUP BY` queries * The ability to validate and mock AggregateResults. Introducing `dfflib_AggregateResult` to overcome Apex's `AggregateResult` construction restriction. [→ Code example](/dfflib/docs/how/selectors#aggregate-queries-group-by-having-soql-functions-) ### Cursor support [#cursor-support] With Spring '26 (API 66) Salesforce introduced [`Database.Cursor`](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_Database_Cursor.htm#apex_class_Database_Cursor) to break down large SOQL query results into manageable chunks, preventing heap size limits or governor limits while processing large volume data. Our Selectors support all Cursor-related `Database` methods, and bring assertion-shortcuts for unit tests. [→ Code example](/dfflib/docs/how/selectors#cursor-and-pagination-cursor-) ### Support for SOQL functions like `DISTANCE`, `TYPEOF` and `FOR`-clauses [#support-for-soql-functions-like-distance-typeof-and-for-clauses] The QueryFactory now supports [`TYPEOF`](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_typeof.htm) (`WHEN [SObjectType] THEN [FieldList]`), the ability to add [`ORDER BY DISTANCE...`](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_geolocate.htm), or to specify for what reason the record is retrieved ([`FOR VIEW`, `FOR REFERENCE`](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_for_view_for_reference.htm) or [`FOR UPDATE`](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_for_update.htm)). This is done through the following new methods and enum: * `DistanceUnit` being a new enum with `MILES` and `KILOMETERS` values * `getDistanceString( SObjectField field, DistanceUnit unit )` * `selectFieldsTypeOf( String field, Map> typeOfMapping )` * `setForView( Boolean )`, `setForReference( Boolean )`, `setForUpdate( Boolean )` * `setAllRows( Boolean allRows )` ### Ability to auto-select (parent/)related fields [#ability-to-auto-select-parentrelated-fields] Comparable to `getSObjectFieldList()` we've added `virtual Set getRelatedFieldSet()` to simplify default inclusion of related (parent-)fields. This is e.g. most useful for junction objects (like PricebookEntry) where you'd always want information from the related Product and Pricebook. * `newQueryFactory( Boolean includeSelectorFields, Boolean includeRelatedFieldSetFields )` ### Performance benefits [#performance-benefits] Selectors 2.0 removes overhead that is rarely needed, reducing CPU time for every query and unit test: * **Simplified field-selection** - With `dfflib_Database.Context` the Field Level Security validation moves to the platform (`USER_MODE`/`SYSTEM_MODE`), so `getFieldPath()` no longer performs regex matching, `SObjectDescribe` lookups and `getDescribe()` calls for each field and relationship. Only legacy constructions where `enforceFLS = true` will still resolve describes to secure with a client-side FLS check; * **Unsorted select fields by default** - Originally, `fflib` would default sort all fields before performing the query, which thus consumed CPU time on each query without a SOQL benefit. Subselects follow the setting of their parent QueryFactory; * **Faster unit tests** - With `mockExecuteQuery()` selector unit tests no longer need to insert data or perform queries, which significantly reduces unit test runtime and data setup boilerplate ([→ Unit test validations](#unit-test-validations)). `dfflib_SObjectSelector.m_sortSelectFields` now defaults to `false` (previously `true`). This only impacts logic depending on the field order, like unit tests comparing the full `toSOQL()` string. If an external system really depends on the sequence, it's recommended to disconnect this dependency via middleware or a wrapper-class. When still really needed, it's possible to call `setSortSelectFields( true )` on a QueryFactory instance to revert to sorting behaviour. ### Correction for `getSObjectType()` and `getSObjectFieldList()` [#correction-for-getsobjecttype-and-getsobjectfieldlist] Per API 65, an `abstract` or `override` method requires a `protected`, `public`, or `global` access modifier. If these aren't explicitly set, the method access defaults to private. Which will cause the (new) Apex compilation error "Abstract methods require at least one of the following: global, public, protected.", since the implementing class would otherwise have no access to the abstract method. Hence, we've added the `protected` access modifier, which impacts all existing implementations, by making the `abstract` method visible and should therefore be overridden when implemented. More information can be found in the [upgrade guide](/dfflib/docs/how/get-started#upgrade). ## Migration & Examples [#migration--examples] Each selector can individually be migrated to D'fflib, allowing a gradual approach. Due to backward compatibility, all original constructions with `enforceFLS`, `FLSEnforcement` and `DataAccess` continue to work as expected. → Click here to read how to leverage D'fflib Database Context and reduce unit test runtime. #### Calling class changes [#calling-class-changes] D'fflib fflib-apex-common ```apex SEL_Assets.newInstance( dfflib_Database.Context.NONE ) .selectCarsBySerialNumber( new Set{ 'SN123', 'SN456' } ); ``` ```apex SEL_Assets.newInstance() .selectCarsBySerialNumber( new Set{ 'SN123', 'SN456' }, false ); ``` #### Selector class changes [#selector-class-changes] Enabling the calling class to define the `dfflib_Database.Context` for the selector instance, allows you to omit the local `WithoutSharing` inner-class and the `withSharing` Boolean parameter. Additionally, it omits the need for local copies of static for bind variables to work, as these can be directly passed into the Map as shown in the example for the recordtype static. D'fflib selector fflib-apex-common selector ```apex public with sharing class SEL_Assets extends dfflib_SObjectSelector{ // [!code word:ctx] public static SEL_Assets newInstance( dfflib_Database.Context ctx ){ // [!code ++] return ( SEL_Assets ) dfflib.selector.newInstance( Asset.SObjectType, ctx ); // [!code ++] } public override Schema.SObjectType getSObjectType(){ return Asset.SObjectType; } public override List getSObjectFieldList(){ return new List{ Asset.AccountId, // ... }; } public List selectCarsBySerialNumber( Set serialNums ){ dfflib_QueryFactory query = newQueryFactory( true ); // [!code ++] query.setCondition( String.join( new List{ 'RecordType.DeveloperName = :carsRecType', 'SerialNumber IN :serialNums' }, ' AND ' ) ); return this.executeQuery( query, new Map{ // [!code ++] 'carsRecType' => DOM_Assets.RECTYPE_CARS, // [!code ++] 'serialNums' => serialNums // [!code ++] } ); // [!code ++] } } ``` ```apex public with sharing class SEL_Assets extends fflib_SObjectSelector{ public static SEL_Assets newInstance(){ // [!code --] return ( SEL_Assets ) Application.selector.newInstance( Asset.SObjectType ); // [!code --] } public override Schema.SObjectType getSObjectType(){ return Asset.SObjectType; } public override List getSObjectFieldList(){ return new List{ Asset.AccountId, // ... }; } // [!code word:withSharing] public List selectCarsBySerialNumber( Set serialNums, Boolean withSharing ){ fflib_QueryFactory query = newQueryFactory( withSharing, withSharing, true ); String carsRecType = DOM_Assets.RECTYPE_CARS; // [!code --] query.setCondition( String.join( new List{ 'RecordType.DeveloperName = :carsRecType', 'SerialNumber IN :serialNums' }, ' AND ' ) ); return ( withSharing ) // [!code --] ? Database.query( query.toSOQL() ) // [!code --] : new WithoutSharing().queryWithFramenumbersAndRecType( query, serialNums, carsRecType ); // [!code --] } public without sharing class WithoutSharing{ // [!code --] public List queryWithFramenumbersAndRecType( fflib_QueryFactory query, Set serialNums, String carsRecType ){ // [!code --] return Database.query( query.toSOQL() ); // [!code --] } // [!code --] } // [!code --] } ``` #### Test class changes [#test-class-changes] Once the D'fflib method `executeQuery()` is called in the Selector it is possible to avoid the query to be performed in unit tests and thoroughly validate the single responsibility of the selector. Before there were three sub-optimal unit test assertion approaches: * Create data and validate a proper return. Causing longer unit-test runtimes. * Use `Limits.getQueryRows()` to assert the number of queries performed. Only validating `Database.query()` but not the query construction. * Implement a `@TestVisible lastQueryFactory` in `fflib_QueryFactory` which is set upon `toSOQL()` to allow assertions Now you can: 1. `mockExecuteQuery()` to avoid database interactions in unit test 2. Leverage `selector.verifyQuery()` with the `SelectorVerificationResults` methods (see next section) 3. Optionally fetch the QueryFactory for additional assertions (like subselects) **Examples of a unit test for a selector method** D'fflib fflib-apex-common with data fflib-apex-common with lastQueryFactory ```apex @IsTest private static void selectCarsBySerialNumber(){ // create mocks to prevent database calls SEL_Assets selector = SEL_Assets.newInstance( dfflib_Database.Context.FULL ); fflib_ApexMocks mocks = selector.mockExecuteQuery(); // Given - setup Set to validate bind-passing Set serialNums = new Set{ '12345' }; // When - perform test selector.selectCarsBySerialNumber( serialNums ); // Then - validate query, condition and fields selector.verifyQueryAndBindVariableKeys( mocks ) .validateCondition( 'SerialNumber IN :serialNums' ) .validateBindVariableValue( 'serialNums', serialNums ) .validateFields( new Set{ Asset.AccountId, Asset.SerialNumber } ); } ``` ```apex @IsTest private static void selectCarsBySerialNumber_Data(){ // Given - create data Asset a = new Asset( SerialNumber = '12345', RecordTypeId = // ... ); insert a; // When - perform test List assList = SEL_Assets.newInstance().selectCarsBySerialNumber( new Set{ a.SerialNumber }, false ); // Then - validate data returned System.Assert.areEqual( 1, assList?.size(), 'Expected one Asset to match the soql criteria' ); } @IsTest private static void selectCarsBySerialNumber_Limits(){ // When - perform test in both contexts (for coverage) SEL_Assets.newInstance().selectCarsBySerialNumber( new Set{ '12345' }, false ); SEL_Assets.newInstance().selectCarsBySerialNumber( new Set{ '12345' }, true ); // Then - validate only one query per context was performed System.Assert.areEqual( 2, Limits.getQueryRows(), 'Expected two queries to be performed, in both contexts' ); } ``` ```apex @IsTest private static void selectCarsBySerialNumber(){ // When - perform test SEL_Assets.newInstance().selectCarsBySerialNumber( new Set{ '12345' }, false ); // Then - validate QueryFactory instance used at last toSOQL() on condition and fields fflib_QueryFactory qf = fflib_QueryFactory.lastQueryFactory; System.assertEquals( 'SerialNumber IN :serialNums', qf.getCondition(), 'Expected different condition string' ); Set queriedFields = qf.getSelectedFields(); Assert.isTrue( queriedFields.contains( 'AccountId' ), 'AccountId is required to check for Asset updates in API' ); Assert.isTrue( queriedFields.contains( 'SerialNumber' ), 'SerialNumber is required to check for match in API input' ); } ``` ## Unit test validations [#unit-test-validations] Each selector class automatically implements the following set of methods to simplify and strengthen unit test assertions:
Method signature Description
  • mockExecuteQuery()
  • mockExecuteAggregateQuery()
Prepares mocking to prevent database calls and initiates (and returns) the fflib_ApexMocks instance. For AggregateQuery the query-calls are automatically stubbed to return List\.
  • verifyQuery( fflib_ApexMocks )
  • verifyQueryLocator( fflib_ApexMocks )
Verifies whether the Query Proxy was called once with a query (locator) and captures the query string. Returns the SelectorVerificationResults instance for further validations.
  • verifyQueryAndBindVariableKeys( fflib_ApexMocks )
  • verifyQueryLocatorAndBindVariableKeys( fflib_ApexMocks )
Verifies whether the Query Proxy was called once with a query (locator) and bind variables and captures the query string and map. Automatically validates whether the bind variable keys in the query string match those in the map (keys). An Assertion is thrown when the number of variables and/or keys don't match. Returns the SelectorVerificationResults instance for further validations.
### SelectorVerificationResults [#selectorverificationresults] To simplify assertions and reduce repetitive code the `SelectorVerificationResults` wrapper was introduced. It contains three variables for extensive validations (like subselects) and a couple frequently occurring methods.
Variable Description
  • dfflib_QueryFactory qf
dfflib_QueryFactory instance used during last toSOQL() .
  • String query
Query string captured from executeQuery() , thus sent to backend.
  • Map map_bindVariables
Map of bind-variables captured from executeQuery() , thus sent to backend.
Method signature Description
  • validateTable( SObjectType sObjType )
Assertion on matching SObjectType table.
  • validateFields( Set fields )
  • validateFields( Set fields )
Assertion on whether all input-fields are included in the QueryFactory. Automatically converts to lowercase to match on deduplicated fields.
  • validateCondition( String expectedCondition )
  • validateCondition( String expectedCondition, Boolean partialMatch )
Assertion on the SOQL condition, with an optional Boolean to allow partial matching.
  • validateBindVariableValue( String bindkey, Object expectedObj )
Assertion on the existence and value of a bind-variable in the captured map.
*→ Click to read more about the Database Context and Proxy implementation, reasoning and benefits.* *→ Click to see more code snippets on how to write selectors with D'fflib, like test method or aggregate result examples.* --- # Test Data Builder Framework URL: /dfflib/docs/what/test-factory-builder-framework/ D'fflib ships a complete Test Data Builder Framework to quickly set up typed, fluent test data — including parent and child relations, formula fields and read-only fields — without touching the database. The Test Data Builder Framework centralises all test data construction behind a single, typed, fluent API. Three output modes cover every testing scenario: pure in-memory mocking (with full formula and read-only field support via a JSON serialisation trick), fake-ID mocking with auto-propagated relationships, and direct database insertion via the Unit of Work. The consistent naming convention, built-in default values and deduplication make test data creation fast, DRY and maintainable across the entire team. Most Salesforce projects eventually accumulate the same pattern: `new Account( Name = 'Test Account' )` scattered across hundreds of test methods. When a required field is added to the object, every test breaks. When a relationship changes, the fix is manual and error-prone. When a developer joins the team, they copy the nearest example and introduce yet another variation of the same construction — often missing required fields, duplicating defaults, or inserting records that could have been mocked. The Test Data Builder Framework eliminates this entirely. All test data construction lives in one place, behind a typed fluent API that reads like a sentence, handles relationships automatically, and gives full control over what ends up in the database — and what doesn't. The framework consists of five collaborating classes: | Class | Responsibility | | --------------------------- | ---------------------------------------------------------------------------- | | `TestFactory` | Single static entry point — `anAccount()`, `aCase()`, `aUser()`, etc. | | `DOM_*Test.Builder` | Project-specific builders — one per SObject, living in the domain test class | | `dfflib_UT_TestFactoryData` | Deduplication key definitions and uniqueness cache | | `dfflib_UT_SObjectFactory` | Core engine — node graph, JSON serialisation, cache, `mock()` / `save()` | | `dfflib_UT_Replacers` | Dynamic merge-field values — `CounterReplacer`, `RandomReplacer` | A companion class `dfflib_UT_Utils` provides additional utilities for common test scenarios (see [below](#companion-utilities)). A step-by-step introduction on how to leverage the framework in practice — mocking layers, structuring test data and writing proper single-responsibility assertions. Have a look at `TestFactory` and `Builders` in domains in our repo to explore the code, methods and comments. ## A brief introduction [#a-brief-introduction] The framework exposes three output modes, each suited to a different testing scenario: | Mode | Method | DB hit? | IDs populated? | Formula & read-only fields? | Use when... | | --------------- | ---------------- | :-----: | :------------: | :-------------------------: | ------------------------------------------------------------------- | | Pure mock | `.mock()` | ✗ | ✗ | ✓ | Unit testing a service or domain method — no database needed | | Mock with IDs | `.mockWithIds()` | ✗ | ✓ (fake) | ✓ | Unit testing logic that reads `.Id` or traverses lookup fields | | Database insert | `.save()` | ✓ | ✓ (real) | ✗ | Integration tests or `@TestSetup` methods that require real records | Wherever the test logic does not require a real database record, prefer `.mock()` or `.mockWithIds()`. This eliminates DML governor limit consumption, removes the need for `@TestSetup`, and makes tests significantly faster — especially when combined with D'fflib's layer mocking via `defineMock()`. ### Single entry point [#single-entry-point] All test data construction starts from `TestFactory` — a class of static factory methods, one per supported SObject. This gives every developer on the team the same starting point, with IDE autocomplete guiding them to the right builder. ```apex TestFactory.anAccount() // → DOM_AccountsTest.Builder TestFactory.aCase() // → DOM_CasesTest.Builder TestFactory.aUser() // → DOM_UsersTest.Builder (pre-configured with asDefault()) TestFactory.anOpportunity() // → DOM_OpportunitiesTest.Builder TestFactory.aProduct() // → DOM_ProductsTest.Builder ``` Note that `aUser()` automatically calls `.asDefault()`, pre-populating locale, timezone and encoding fields — the most common source of missing required fields on User records in test classes. ### Fluent builder API with consistent naming conventions [#fluent-builder-api-with-consistent-naming-conventions] Every builder follows the same naming convention, making the intent of each method immediately readable and predictable across the entire codebase: | Prefix | Purpose | Example | | ------ | ------------------------------------------------ | ------------------------------------------------------ | | `as` | Scenario shortcut — sets multiple fields at once | `asDefault()`, `asStandard( 'Product A' )`, `asTest()` | | `for` | Parent lookup — links to another builder | `forAccount( accountBuilder )` | | `add` | Child relationship — attaches a child builder | `addContact( contactBuilder )` | | `is` | Boolean field | `isClosed( true )`, `isActive()` | | `with` | Any other field — typed by field token | `withName( 'Acme' )`, `withCloseDate( today )` | Named `with*()` methods use `SObjectField` tokens for compile-time safety and IDE navigation. A generic `with( SObjectField, value )` overload is also available as a catch-all for fields that don't have a dedicated named method: ```apex // Named method — preferred for readability TestFactory.anAccount().withName( 'Acme Corp' ) // Generic overload — useful for less common fields TestFactory.anAccount().with( Account.Rating, 'Hot' ) ``` A string-based escape hatch exists on some builders for fields where a token is not available at compile time: ```apex // String-based fallback — use only when SObjectField token is unavailable TestFactory.aCase().with( 'CustomField__c', 'value' ) ``` All builder methods, except the inherited methods `mock()`, `mockWithIds()` and `save()`, return `this`, enabling full method chaining: ```apex Account acc = ( Account ) TestFactory.anAccount() .withName( 'Acme Corp' ) .mock(); ``` ### Relationship graph — parents, children, bidirectional [#relationship-graph--parents-children-bidirectional] The framework models the full relationship graph between records. Parent lookups and child collections are registered on the builder and resolved automatically — whether mocking or saving. **Child relationships** use `addChild( SObjectField lookupOnChild, BuilderBase child )`, where the field token is the lookup field on the child pointing back to the parent: ```apex // DOM_AccountsTest.Builder — Contact.AccountId is the lookup on Contact pointing to Account public DOM_AccountsTest.Builder addContact( DOM_ContactsTest.Builder cBuilder ){ addChild( Contact.AccountId, cBuilder ); return this; } ``` **Parent relationships** use `setParent( SObjectField lookupOnThis, BuilderBase parent )`: ```apex // DOM_CasesTest.Builder — Case.AccountId is the lookup on Case pointing to Account public DOM_CasesTest.Builder forAccount( DOM_AccountsTest.Builder builder ){ setParent( Case.AccountId, builder ); return this; } ``` When saving, the framework delegates to the Unit of Work and resolves the correct DML insertion order automatically — no manual `registerNew` / `registerRelationship` calls needed. When calling `.mockWithIds()`, the framework traverses the full relationship tree, assigns fake IDs (via `fflib_IDGenerator`) to every node, and populates all lookup fields bidirectionally. A cycle-detection guard (stack depth limit of 5) prevents infinite recursion on circular references. Mock with IDs Save to database Complex hierarchy ```apex // Fake IDs auto-assigned and propagated through the full relationship tree DOM_AccountsTest.Builder accBuilder = TestFactory.anAccount(); DOM_ContactsTest.Builder conBuilder = TestFactory.aContact() .forAccount( accBuilder ); Contact con = ( Contact ) conBuilder.mockWithIds(); // Both records have fake IDs; Contact.AccountId is populated System.Assert.isNotNull( con.Id ); System.Assert.isNotNull( con.AccountId ); ``` ```apex // Full database insertion — relationships resolved automatically via Unit of Work Account acc = ( Account ) TestFactory.anAccount() .addContact( TestFactory.aContact().withName( 'Jane Doe' ) ) .save(); // acc.Id is a real Salesforce ID; the Contact is inserted and linked System.Assert.isNotNull( acc.Id ); ``` ```apex // Full hierarchy: Account → Opportunity → OpportunityLineItem ← Product DOM_AccountsTest.Builder accBuilder = TestFactory.anAccount() .withName( 'Acme Corp' ); DOM_ProductsTest.Builder productBuilder = TestFactory.aProduct() .asStandard( 'Enterprise License' ); Opportunity opp = ( Opportunity ) TestFactory.anOpportunity() .forAccount( accBuilder ) .addOppLineitem( TestFactory.anOpportunityLineItem() .forProduct( productBuilder ) ) .save(); ``` ### Scenario presets via `as*()` methods [#scenario-presets-via-as-methods] Where applicable, builders expose `as*()` methods that set a meaningful combination of fields in one call — keeping test classes readable and preventing callers from having to know which fields constitute a valid scenario. Not every builder needs an `as*()` method; they are only added when a meaningful business scenario warrants it. ```apex // DOM_UsersTest.Builder — asDefault() sets all required locale and encoding fields public DOM_UsersTest.Builder asDefault(){ set( User.EmailEncodingKey, 'UTF-8' ); set( User.LanguageLocaleKey, 'nl_NL' ); set( User.LocaleSidKey, 'en_US' ); set( User.TimeZoneSidKey, 'Europe/Amsterdam' ); this.isActive( true ); return this; } ``` `as*()` methods can also compose other builders, making complex scenarios concise: ```apex // DOM_AccountsTest.Builder — asAdministrative() sets record type + name in one call public DOM_AccountsTest.Builder asAdministrative(){ forRecordType( TestFactory.aRecordType().withDeveloperName( 'Administrative' ) ); withName( 'Do Not Delete' ); return this; } // DOM_ProductsTest.Builder — asStandard() activates the product and adds a standard pricebook entry public DOM_ProductsTest.Builder asStandard( String productName ){ set( Product2.Name, productName ); isActive(); addEntry( new DOM_PricebookEntriesTest.Builder().forPricebook( new DOM_PricebooksTest.Builder().asTest() ) ); return this; } ``` When a scenario should always be applied for a given SObject — such as `User` always needing locale and encoding fields — pre-wire the `as*()` call in `TestFactory` so callers never have to remember it: ```apex // TestFactory.cls — asDefault() pre-wired, callers get a valid User automatically public static DOM_UsersTest.Builder aUser(){ return new DOM_UsersTest.Builder().asDefault(); } ``` For fields that must be unique across records, `dfflib_UT_Replacers` generate dynamic values at evaluation time — not at definition time. These can be used directly inside `as*()` methods or `set()` calls: * **`CounterReplacer`** — increments a per-field, per-SObjectType counter each time a record is created. `new CounterReplacer( 'Test Account {0}' )` → `'Test Account 0'`, `'Test Account 1'`, ... * **`RandomReplacer`** — generates a random alphanumeric string of a given length. `new RandomReplacer( 'TEST{0}', 8 )` → `'TEST47297486'` ```apex // Inside an as*() method — unique username and nickname per User record set( User.Username, new dfflib_UT_Replacers.CounterReplacer( 'unittestuser{0}@fflibfast.com' ) ); set( User.CommunityNickname, new dfflib_UT_Replacers.RandomReplacer( 'TEST{0}', 8 ) ); ``` ### The JSON serialisation trick — formula and read-only fields [#the-json-serialisation-trick--formula-and-read-only-fields] This is the most important technical capability of the framework, and the reason `.mock()` is so powerful for unit testing. In Apex, formula fields, rollup summaries, and system-managed fields (like `CreatedDate`, relationship objects, or auto-calculated values) cannot be written to directly. Attempting to set them on an SObject instance throws a runtime exception. This makes it impossible to test logic that reads these fields without inserting a real record — which is slow, consumes DML limits, and often requires complex setup. The framework bypasses this restriction entirely. When `.mock()` is called, the engine: 1. Serialises the full node graph (fields, parents, children) to a `Map` 2. Calls `JSON.serialize()` on that map 3. Calls `JSON.deserialize()` back to the typed SObject Apex's JSON deserialiser does not enforce field-level write restrictions. The result is a fully populated SObject instance with formula fields, rollup values, and read-only fields set to whatever values the builder specified — without a single DML operation. With read-only fields (.mock()) Without the framework ```apex // Opportunity.Amount is auto-calculated from child OLIs — not writable in Apex // With mock(), it can be set directly on the builder public DOM_OpportunitiesTest.Builder asWithAmount( Decimal amount ){ set( Opportunity.Name, 'Test Opportunity' ); set( Opportunity.StageName, 'Nieuw' ); set( Opportunity.CloseDate, System.today().addDays( 1 ) ); set( Opportunity.Amount, amount ); // read-only field — populated via mock() return this; } // In the test class — no DML, no SOQL, Amount is populated Opportunity opp = ( Opportunity ) TestFactory.anOpportunity() .asWithAmount( 50000 ) .mock(); System.Assert.areEqual( 50000, opp.Amount ); ``` ```apex // Direct construction — read-only fields cannot be set Opportunity opp = new Opportunity( Name = 'Test Opportunity', StageName = 'Nieuw', CloseDate = System.today().addDays( 1 ) // Amount = 50000 ← runtime exception: field is not writeable ); // Only option without the framework: insert child OLIs and re-query // — costs DML, a SOQL query, and all required fields must be set insert opp; opp = [ SELECT Id, Amount FROM Opportunity WHERE Id = :opp.Id ]; ``` Any method that branches on a formula field, a rollup summary, or a system field can be tested in full — without a database — by setting it on the builder via an `as*()` method. This is the single most impactful reason to adopt `.mock()` over inline SObject construction for unit tests. The same trick is applied in `dfflib_UT_Utils` to construct `Database.SaveResult`, `Database.DeleteResult` and `Database.UndeleteResult` instances — system types that Apex forbids direct construction of (see [Companion utilities](#companion-utilities)). ## How it works [#how-it-works] Step-by-step guidance on structuring test data, mocking layers and writing proper single-responsibility assertions. *Click to read more.* The full set of D'fflib utility methods and shortcuts — including `dfflib_UT_Utils` and `defineMock()`. *Click to read more.* ## Companion utilities [#companion-utilities] `dfflib_UT_Utils` provides a set of ready-to-use utility methods for common test scenarios that complement the builder framework: * **`dfflib_UT_Utils.getCurrentUser()`** — returns a `User` record for the current user without a SOQL query. Useful when a `User` instance is needed as a variable — for example, to pass into `System.runAs()` or to assert against `UserInfo.getUserId()`. * **`dfflib_UT_Utils.createSObjectList( SObject sObj, Integer n )`** — clones an SObject instance `n` times. Optionally inserts immediately with `createSObjectList( sObj, n, true )`. * **`dfflib_UT_Utils.getProfile( String name )`** / **`getProfileId( String name )`** — retrieves a Profile by name with internal caching to avoid repeated queries across test methods. * **`dfflib_UT_Utils.createSaveResult( Id recordId, Boolean success, String message )`** — constructs a mock `Database.SaveResult` instance. Apex does not allow direct construction of `Database.SaveResult` — this method applies the same JSON serialisation trick as `.mock()` to bypass the restriction. * **`dfflib_UT_Utils.createDeleteResult( Id recordId, Boolean success, String message )`** — same pattern for `Database.DeleteResult`. * **`dfflib_UT_Utils.createUndeleteResult( Id recordId, Boolean success, String message )`** — same pattern for `Database.UndeleteResult`. The `createSaveResult`, `createDeleteResult` and `createUndeleteResult` methods apply the same JSON serialisation trick as `.mock()` — bypassing Apex's constructor restrictions on these system types. This enables testing of error-handling logic that branches on `SaveResult.isSuccess()` or inspects `SaveResult.getErrors()` without performing any actual DML. ```apex // Construct a failed SaveResult — impossible via direct instantiation in Apex Database.SaveResult failedResult = dfflib_UT_Utils.createSaveResult( fflib_IDGenerator.generate( Account.SObjectType ), false, 'Insufficient permissions' ); System.Assert.isFalse( failedResult.isSuccess() ); System.Assert.areEqual( 'Insufficient permissions', failedResult.getErrors()[ 0 ].getMessage() ); ``` --- # Trigger Framework URL: /dfflib/docs/what/trigger-framework/ D'fflib comes with an extended trigger framework, enabling bulkified, scalable and maintainable trigger handlers. D'fflib enforces one trigger per SObject, delegating all orchestration to the Domain class. Handlers are registered per trigger event, executed in a structured three-phase lifecycle (initialize → process → finalize), and share a single Unit of Work commit — keeping your trigger logic bulkified, testable, and free of scattered DML. ## Main benefits [#main-benefits] ### Simplified and standardised trigger initiation [#simplified-and-standardised-trigger-initiation] Each trigger directly delegates to the Domain class with the one-liner `dfflib_SObjectDomain.triggerHandler( [class] )`. ### Clearer handler separation and management [#clearer-handler-separation-and-management] Handlers are centrally registered in the Domain constructor, defining execution order and event coverage. Encouraging trigger logic to be split to handlers with single- and clear responsibilities. One Handler can be easily registered to multiple trigger events, encouraging reuse and avoiding duplicate code. ### Bulkified architecture [#bulkified-architecture] Each handler follows a three-phase lifecycle:
  1. Single `initialize()` for preparing data in bulk (like queries and other loops)
  2. Per record `process()` allowing clean execution of the handler's main operation
  3. Single `finalize()` for concluding the logic and saving back to the database (in bulk)
This encourages bulkified handlers with no SOQL and DML inside loops and easy to understand and manage logic.
### Built-in transaction management [#built-in-transaction-management] All handlers share the same `dfflib_ISObjectUnitOfWork` instance injected by the framework. Work is registered across handlers and committed after all handlers have completed. This enables grouping records and eliminating repetitive DML round-trips and governor limit pressure. Additionally, this simplifies testing and mocking, aside from centralised and built-in transaction management. Avoiding the need for Rollback and Exception handling scattered across the trigger. ### Execution control [#execution-control] Handlers explicitly implement one or multiple `TriggerEvent` interfaces and opt. `FireOnce` to control execution. Ensuring records are only processed once per transaction and avoiding duplicate work across trigger events. ### Isolated, independently testable handlers [#isolated-independently-testable-handlers] Because each handler is a self-contained inner class with a clear interface, it can be instantiated and tested in isolation without firing the full trigger stack. This dramatically reduces test setup complexity.
We're currently finalising the migration for Trigger Handler registrations from Domain constructor to metadata. Simplifying registration and giving more flexibility to enable/disable handlers without code changes. *** Step-by-step guide to configuring your Domain class, including constructor setup and handler registration. Walkthrough for creating BaseHandler implementations, applying FireOnce, and structuring the three-phase lifecycle. ## What it brings [#what-it-brings] ### The Domain as trigger orchestrator [#the-domain-as-trigger-orchestrator] The trigger itself is a one-liner. It delegates immediately to the Domain class, which owns all orchestration: ```apex trigger AccountsTrigger on Account (before insert, before update, before delete, after insert, after update, after delete, after undelete) { dfflib_SObjectDomain.triggerHandler(DOM_Accounts.class); } ``` The Domain constructor is where handlers are registered. Each `registerHandler` call binds a `TriggerEvent` to a handler class: ```apex public with sharing class DOM_Accounts extends dfflib_SObjectDomain implements IDomain { public DOM_Accounts(List records) { super(records, dfflib.unitOfWork.newInstance()); registerHandler(TriggerEvent.AFTER_INSERT, SyncAccountToERP.class); registerHandler(TriggerEvent.AFTER_UPDATE, SyncAccountToERP.class); } public class Constructor implements dfflib_SObjectDomain.IConstructable { public dfflib_SObjectDomain construct(List sObjectList) { return new DOM_Accounts(sObjectList); } } } ``` See [Domain setup](/dfflib/docs/how/domains) for the full Domain class configuration. *** ### Handler anatomy: initialize → process → finalize [#handler-anatomy-initialize--process--finalize] Every handler extends `BaseHandler` and optionally overrides three lifecycle methods. The framework calls them in order for every trigger invocation: ```apex public class CalculateTotalPrice extends BaseHandler implements BeforeInsert, BeforeUpdate{ // Called once before record iteration — use for bulk queries and setup public override void initialize( TriggerState ts, dfflib_ISObjectUnitOfWork uow ){ // e.g. pre-load related records from a selector } // Called once per record — no SOQL, no DML public override Boolean process( SObject current, SObject original, dfflib_ISObjectUnitOfWork uow ){ RoomReservation__c newRecord = ( RoomReservation__c ) current; RoomReservation__c oldRecord = ( RoomReservation__c ) original; // register work on uow, return true if this record was processed return true; } // Called once after record iteration public override void finalize( TriggerState state, dfflib_ISObjectUnitOfWork uow ){ // e.g. call Domain method, Log } } ``` The `process()` return value feeds into `FireOnce` deduplication (see below). Returning `true` signals the record was handled; returning `false` leaves it eligible for re-processing in a subsequent trigger invocation. *** ### TriggerState — bulk context across phases [#triggerstate--bulk-context-across-phases] A `TriggerState` instance is injected into both `initialize()` and `finalize()`. It acts as a shared context object for the handler's full lifecycle — allowing data loaded in `initialize()` (e.g. a map of related records) to be available in `finalize()` without passing it through `process()`. This keeps the per-record method signature clean while still supporting bulk patterns. ```apex public class TriggerState{ public final List currentList; public final List originalList; } ``` *** ### FireOnce — smart deduplication [#fireonce--smart-deduplication] Handlers that implement `FireOnce` are only executed once per record per transaction. If `process()` returns `true` for a record, that record is skipped on any subsequent trigger invocation within the same transaction. ```apex public class SyncAccountToERP extends BaseHandler implements FireOnce, AfterInsert, AfterUpdate { // ... } ``` *** ### Trigger event coverage [#trigger-event-coverage] Register handlers against any of the following `TriggerEvent` enum values: | Enum value | Trigger context | | ---------------- | ------------------ | | `BEFORE_INSERT` | Before insert | | `BEFORE_UPDATE` | Before update | | `BEFORE_DELETE` | Before delete | | `AFTER_INSERT` | After insert | | `AFTER_UPDATE` | After update | | `AFTER_DELETE` | After delete | | `AFTER_UNDELETE` | After undelete | | `ALL` | All trigger events | Each enum value has a corresponding interface (`BeforeInsert`, `AfterUpdate`, `AllEvents`, etc.) that the handler implements to declare which events it responds to. --- # Get started URL: /dfflib/docs/how/get-started/ Learn how to easily install, upgrade or update D'fflib in your Salesforce environment, and what is needed to maximise framework benefits. ## Adoption paths [#adoption-paths] To simplify this guide, we distinguish three scenarios for your Salesforce environment: **Fresh install** (\~5 min)\ No (D')fflib installed yet, either on a fresh or existing project. **Migrate** (\~1 day)\ Any fflib version is installed and you want to promote/migrate to D'fflib. **Upgrade** (\~30 min)\ A D'fflib version is installed and you want to upgrade to a later version. ## Distributions [#distributions] Additionally, we distinguish three installation approaches: **D'fflib** Recommended\ One unlocked package, including `fflib-apex-common`, `fflib-apex-mocks`, and all D'fflib extensions. Recommended as it improves the developer experience due to easy upgrade, reduced package-maintenance and no local dependency control. **D'fflib BYO** (Bring Your Own fflib)\ One org-dependent unlocked package with all D'fflib extensions. Granting projects control of which fflib version is applied, including possible customisations. **Manual** (optionally cherry-pick)\ D'fflib classes are cloned/retrieved and added to the codebase, following projects' release process. Full flexibility, control and responsibility over which parts of D'fflib are included. Check the FAQ for more installation considerations like: ## Installation guide [#installation-guide] Based on your situation and preferred distribution, you can find the relevant guide: | Your situation | D'fflib Recommended | D'fflib BYO | Manual | | -------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------ | ----------------------------------------------------------------- | | Fresh | 1. [Fresh install](#fresh-install) (\~5 min) | 1. Deploy fflib classes;
2. [Fresh install](#fresh-install) | [Repository](https://github.com/deloitte-engineering/dfflib-code) | | Migrate | 1. [Migrate](#migrate-from-fflib) (\~1 day) | 1. Check [prerequisites](#byo-prerequisites);
2. [Migrate](#migrate-from-fflib) | [Repository](https://github.com/deloitte-engineering/dfflib-code) | | Upgrade | 1. [Upgrade](#upgrade) (\~30 min) | [Upgrade](#upgrade) | [Upgrade](#upgrade) by
applying changes | Before deploying (D')fflib, it is essential to have a clear idea with regard to: Installing the package itself won't change code quality. You'll need to **start absorbing and applying the patterns** to realise the benefits. Regardless of the starting point, **developers should be trained and enabled** to ensure they can maximise the benefits of D'fflib, and thus ensure scalable and maintainable Salesforce features. *** ### Fresh install [#fresh-install] Install via the unlocked package installation link in the [GitHub releases page](https://github.com/deloitte-engineering/dfflib-code/releases). During installation, select the following options for the best experience: * Install for Admins only * Only compile classes of the package (in the advanced settings section)
Installation options
```bash sf package install \ --package \ --target-org \ --security-type AdminsOnly \ --apex-compile package \ --wait 10 ```
Wait for the installation to complete and check the [next steps](#next-steps) .
When the Contact Request object isn't available in the org, the package will fail. This is a standard object that should be available in all orgs. However, some older orgs might not have it enabled. The resolution is to raise a Salesforce support case to enable this object. To reduce project dependencies all D'fflib database unit tests have been rewritten to less commonly configured objects: `ContactRequest` and `Solution`. When your project has required fields, validation rules or automation to these objects, the data insertion during unit test might fail, typically with `REQUIRED_FIELD_MISSING` or `FIELD_CUSTOM_VALIDATION_EXCEPTION`. To avoid the need for Apex changes, it is possible to inject base records via `Dfflib_Config__mdt`: 1. Create one `Dfflib_Config__mdt` record and provide a JSON including the required field or to pass validation. 2. The unit test deserialises this JSON and clones it for every sample record. Leave a field blank to keep the framework default. Note, only the first `Dfflib_Config__mdt` is used, so ensure there is always 0 or 1 record. Solution ContactRequest Dfflib_Config.Default.md-meta.xml ```json lineNumbers { "SolutionName": "SolutionName", "IsPublished": false, "Status": "Draft", "Your_Required_Field__c": "Sample value" } ``` ```json lineNumbers { "RequestDescription": "Unit test contact request", "Your_Required_Field__c": "Sample value" } ``` ```xml lineNumbers false Test_Solution_Sample_Record_Data__c {"SolutionName":"SolutionName","IsPublished":false,"Status":"Draft"} ``` *** ### Migrate from fflib [#migrate-from-fflib] D'fflib is designed to be backward compatible, so migration from fflib should be relatively straightforward. Below are the recommended steps for a quick, easy and clear path towards a compiling environment. Adoption of D'fflib features in existing code is optional and can follow your own timelines, using the per-layer [migration steps](#migrate-layer-specific-steps). * **Determine project customisations**\ Check your repository history or compare your classes with [`fflib-apex-common`](https://github.com/apex-enterprise-patterns/fflib-apex-common) and [`fflib-apex-mocks`](https://github.com/apex-enterprise-patterns/fflib-apex-mocks) to identify customisations. Validate today's relevancy, like whether they can be superseded by D'fflib features. If still needed, document them in a customisation overview (class, reason and change), which every future [upgrade](#upgrade) relies on. * **Check fflib dependencies** D'fflib BYO\ Make sure your version of fflib meets all [BYO prerequisites](#byo-prerequisites). If not, manually add the missing variables and methods. * Validate whether all Apex classes compile and unit tests pass. If not, resolve them, or document which fail. * Follow above [Fresh install](#fresh-install) steps in a separate or DEV sandbox. * Check the [known issues](#known-migration-issues) and apply code refactorings as needed (like adding `override` to all Selectors). * If you had customisations, retrieve the latest class version from the org, re-apply the customisation and deploy it to override. Make sure to add your customisations to your customisation overview and your deployment process. Validate whether your enrichment could benefit others. If so, [let us know](/dfflib/docs/faq#contributing-improvements-new-features). * Compile all classes and run all unit tests. * With the (full) D'fflib package, classes don't need to be part of your regular deployments and releases. Thus, the Application and all `fflib_`-prefixed classes can be removed from your repository. Don't add them to destructive changes, as the package still needs them. * For D'fflib BYO the classes should logically be kept in your repository. Migration can be done per layer and class. Though with below anonymous apex script you can automatically create and deploy all `Dfflib_[layer]_Config__mdt` metadata records. ```apex // ================================ CONFIGURE ================================ Boolean dryRun = true; // true: only debug the records, false: enqueue the deployment String objectPrefix = ''; // optional prefix of the custom metadata object API names Integer uowSortOrderStep = 10; // SortOrder__c increment for the Unit of Work records // Point to the factories of your application class, set one to null to skip it fflib_Application.UnitOfWorkFactory sourceUnitOfWork = fflib.unitOfWork; fflib_Application.SelectorFactory sourceSelector = fflib.selector; fflib_Application.DomainFactory sourceDomain = fflib.domain; fflib_Application.ServiceFactory sourceService = fflib.service; // =========================================================================== // Readers: a subclass may access the protected maps of the factories, so fflib_Application stays untouched public class UnitOfWorkReader extends fflib_Application.UnitOfWorkFactory{ public List read( fflib_Application.UnitOfWorkFactory source ){ return source.m_objectTypes; } } public class SelectorReader extends fflib_Application.SelectorFactory{ public Map read( fflib_Application.SelectorFactory source ){ return source.m_sObjectBySelectorType; } } public class DomainReader extends fflib_Application.DomainFactory{ public Map read( fflib_Application.DomainFactory source ){ return source.constructorTypeByObject; } } public class ServiceReader extends fflib_Application.ServiceFactory{ public Map read( fflib_Application.ServiceFactory source ){ return source.m_serviceInterfaceTypeByServiceImplType; } } // Builds valid custom metadata records and collects them in one deploy container public class RecordBuilder{ public Metadata.DeployContainer container = new Metadata.DeployContainer(); public Integer recordCount = 0; private String objectPrefix; private Set usedFullNames = new Set(); public RecordBuilder( String objectPrefix ){ this.objectPrefix = objectPrefix == null ? '' : objectPrefix; } public void add( String typeName, String recordName, String label, Map valueByField ){ String baseName = toDeveloperName( recordName ); String developerName = baseName; Integer suffix = 2; while( usedFullNames.contains( typeName + '.' + developerName ) ){ String suffixText = '_' + suffix++; developerName = baseName.left( 40 - suffixText.length() ).removeEnd( '_' ) + suffixText; } usedFullNames.add( typeName + '.' + developerName ); Metadata.CustomMetadata record = new Metadata.CustomMetadata(); record.fullName = objectPrefix + typeName + '.' + developerName; record.label = label.left( 40 ); for( String field : valueByField.keySet() ){ Metadata.CustomMetadataValue fieldValue = new Metadata.CustomMetadataValue(); fieldValue.field = field; fieldValue.value = valueByField.get( field ); record.values.add( fieldValue ); } container.addMetadata( record ); recordCount++; System.debug( '*** ' + record.fullName + ' [' + record.label + '] ' + valueByField ); } // DeveloperName: max 40 chars, alphanumeric and underscores, starts with a letter, no double or trailing underscores private String toDeveloperName( String value ){ String name = value.replaceAll( '[^A-Za-z0-9]+', '_' ).replaceAll( '^_+|_+$', '' ); if( String.isBlank( name ) || !name.left( 1 ).isAlpha() ){ name = 'X_' + name; } return name.left( 40 ).removeEnd( '_' ); } } RecordBuilder builder = new RecordBuilder( objectPrefix ); // Domain entries if( sourceDomain != null ){ Map domainMapping = new DomainReader().read( sourceDomain ); for( Object key : domainMapping.keySet() ){ if( !( key instanceof SObjectType ) ){ System.debug( '*** Skipped domain ' + key + ': only SObjectType keys are supported by Dfflib_Domain_Config__mdt' ); continue; } SObjectType objType = ( SObjectType ) key; String objTypeString = String.valueOf( objType ); builder.add( 'Dfflib_Domain_Config', objTypeString, objType.getDescribe().getLabel(), new Map{ 'SObjectType__c' => objTypeString, 'Implementation_Type__c' => domainMapping.get( key ).getName(), 'Is_Trigger_Disabled__c' => false } ); } } // Selector entries if( sourceSelector != null ){ Map selectorMapping = new SelectorReader().read( sourceSelector ); for( SObjectType objType : selectorMapping.keySet() ){ String objTypeString = String.valueOf( objType ); builder.add( 'Dfflib_Selector_Config', objTypeString, objType.getDescribe().getLabel(), new Map{ 'SObjectType__c' => objTypeString, 'Implementation_Type__c' => selectorMapping.get( objType ).getName() } ); } } // Service entries, named after the interface as that is the lookup key if( sourceService != null ){ Map serviceMapping = new ServiceReader().read( sourceService ); for( Type interfaceType : serviceMapping.keySet() ){ String interfaceName = interfaceType.getName(); builder.add( 'Dfflib_Service_Config', interfaceName, interfaceName, new Map{ 'Interface_Type__c' => interfaceName, 'Implementation_Type__c' => serviceMapping.get( interfaceType ).getName() } ); } } // Unit of Work entries, keeping the order of the legacy list if( sourceUnitOfWork != null ){ List uowTypes = new UnitOfWorkReader().read( sourceUnitOfWork ); for( Integer i = 0; uowTypes != null && i < uowTypes.size(); i++ ){ String objTypeString = String.valueOf( uowTypes[ i ] ); builder.add( 'Dfflib_UOW_Config', objTypeString, uowTypes[ i ].getDescribe().getLabel(), new Map{ 'SObjectType__c' => objTypeString, 'SortOrder__c' => Decimal.valueOf( ( i + 1 ) * uowSortOrderStep ) } ); } } if( builder.recordCount == 0 ){ System.debug( '*** Nothing to deploy' ); } else if( dryRun ){ System.debug( '*** Dry run: ' + builder.recordCount + ' records prepared, nothing deployed. Set dryRun = false to deploy.' ); } else{ // No callback: an Anonymous Apex callback class makes the deployment fail with UNKNOWN_EXCEPTION Id jobId = Metadata.Operations.enqueueDeployment( builder.container, null ); System.debug( '*** Deployment of ' + builder.recordCount + ' records enqueued, job Id: ' + jobId ); } ``` * Layers can be migrated based on capacity and priorities to leverage D'fflib features. * Check the [Adoption guide](/dfflib/docs/how/adoption) for the recommended sequence of migrating layers. **Migration steps**: **Start leveraging** * Check the [next steps](#next-steps) to learn more about application and adoption tips. *** Known migration issues Due to some breaking changes in Salesforce APIs, upgrading fflib to the latest API (e.g. by migrating to D'fflib) will likely cause compilation and runtime errors. Read how to best mitigate these, taking different urgencies and contexts into account. **Cause**: * All classes running API v67.0+ follow the [new default sharing mode enforcement](https://help.salesforce.com/s/articleView?id=release-notes.rn_apex_default_enforce_sharing.htm\&release=262\&type=5): when the class omits to define a sharing mode, it will run `with sharing`. * All Database operations running API v67.0+ follow the [new default user mode](https://help.salesforce.com/s/articleView?id=release-notes.rn_apex_default_user_mode.htm\&release=262\&type=5): when no access mode is specified, it will run in user mode. * Since all D'fflib classes run on the latest API version, this is immediately applied. **Consequence**: * fflib selector methods apply the default of the Selector class API version, as `Database.query()` is called within that class. If you don't update the Selector class API version, there will be no change. * D'fflib selector methods run on API v67.0+, as the query is offloaded to the Database Proxy. If you migrate, without defining a `Context`, access or sharing mode, the new default will apply. * Database operations apply the default of the Unit of Work API version which for D'fflib is API v67.0+. Thus enforcing sharing, CRUD and FLS permissions when no `Context`, access or sharing mode is defined. **Options** (in order of recommendation): 1. Migrate code to D'fflib features and apply `dfflib_Database.Context` to always have an access and sharing mode defined. See [Context enum](/dfflib/docs/what/database-context#database-context-enum) for the possibilities. 2. Ensure all classes and database operations define an explicit access and sharing mode, like passing an `IDML` instance to the Unit of Work. 3. To (temporarily) buy time and allow gradual technical debt mitigation: retrieve the `dfflib_SObjectUnitOfWork` and `dfflib_Database_Proxy` classes after installation, downgrade their API versions to v66.0 and override the D'fflib files via your deployment process. **Cause**: * Per API v65.0+ ([Winter '26](https://developer.salesforce.com/docs/platform/apex-dev/references/apex-dev/apex-classes-access-modifiers.html#versioned-behavior-changes)), `abstract` and `override` methods must be declared `public`, `protected` or `global`. If none is specified, the methods default to `private`, preventing the implementing class from accessing them. **Consequence**: * In `fflib_SObjectSelector` the `getSObjectType()` and `getSObjectFieldList()` methods did not have an explicit access modifier, thus, defaulting to `private`. To keep these methods available for Selectors, they were set to `public` and `protected`. * However, this made them available to all inheriting classes, which required the `override` keyword to be used in the selector implementations. **Fix**: * Find-and-replace the methods to prepend the `override` keyword. Before After ```apex Schema.SObjectType getSObjectType() List getSObjectFieldList() ``` ```apex // [!code word:override] override Schema.SObjectType getSObjectType() override List getSObjectFieldList() ``` **Eliminate downtime**: Note, this can cause compilation errors/downtime in your Production org between the package installation (overriding framework code) and the completion of your deployment (including the `override` changes). If this compilation-error window can't be scheduled at an acceptable time: 1. Retrieve the D'fflib code (`dfflib_SObjectSelector` or the full package) to your project repository 2. Deploy it together with the selector `override` changes 3. Install the package 4. Remove the D'fflib code from your project repository (no destructive changes) This eliminates any downtime, maintains compilation continuity and ensures a smooth unlocked package installation. *** BYO prerequisites D'fflib BYO (Bring Your Own) is an org-dependent unlocked package. It relies on the `fflib-apex-common` and `fflib-apex-mocks` classes to exist in your org, so it can't compile on its own and is only validated when installed in your org. All referenced methods and classes must therefore be present. Search your repository for the classes and signatures listed below. * Anything you can't find means your copy predates that change and should be (manually) added. Update the affected classes from the upstream repository before installing D'fflib BYO, and be conscious to not override any local customisation. * Given the sorting from new to old, it is likely all changes below the first match are included. Though this does depend on the maintenance and adoption of your codebase. | Introduced | Classes and signatures introduced | | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Nov 2026](https://github.com/apex-enterprise-patterns/fflib-apex-common/pull/539) (#539) | Method [`fflib_SObjectDescribe.getNameField(Schema.SObjectType)`](https://github.com/apex-enterprise-patterns/fflib-apex-common/blob/master/sfdx-source/apex-common/main/classes/fflib_SObjectDescribe.cls) | | [Sep 2026](https://github.com/apex-enterprise-patterns/fflib-apex-common/pull/536) (#536) | Exception [`fflib_Objects.InvalidValueException`](https://github.com/apex-enterprise-patterns/fflib-apex-common/blob/master/sfdx-source/apex-common/main/classes/fflib_Objects.cls) | | [Apr 2021](https://github.com/apex-enterprise-patterns/fflib-apex-common/pull/300) (#300) | Class [`fflib_IObjects`](https://github.com/apex-enterprise-patterns/fflib-apex-common/blob/master/sfdx-source/apex-common/main/classes/fflib_IObjects.cls), [`fflib_Objects`](https://github.com/apex-enterprise-patterns/fflib-apex-common/blob/master/sfdx-source/apex-common/main/classes/fflib_Objects.cls), [`fflib_ISObjects`](https://github.com/apex-enterprise-patterns/fflib-apex-common/blob/master/sfdx-source/apex-common/main/classes/fflib_ISObjects.cls), [`fflib_SObjects`](https://github.com/apex-enterprise-patterns/fflib-apex-common/blob/master/sfdx-source/apex-common/main/classes/fflib_SObjects.cls), [`fflib_IDomain`](https://github.com/apex-enterprise-patterns/fflib-apex-common/blob/master/sfdx-source/apex-common/main/classes/fflib_IDomain.cls) | | [Apr 2017](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/pull/34) (#34) | Class [`fflib_VerificationMode`](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/blob/master/sfdx-source/apex-mocks/main/classes/fflib_VerificationMode.cls)
Method: [`fflib_ApexMocks.calls(Integer)`](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/blob/master/sfdx-source/apex-mocks/main/classes/fflib_ApexMocks.cls), [`fflib_InOrder.verify(Object, fflib_VerificationMode)`](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/blob/master/sfdx-source/apex-mocks/main/classes/fflib_InOrder.cls) | | [Mar 2017](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/pull/32) (#32) | Class [`fflib_InOrder`](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/blob/master/sfdx-source/apex-mocks/main/classes/fflib_InOrder.cls) | | [Feb 2017](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/pull/28) (#28) | Method [`fflib_ApexMocks.mock(Type)`](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/blob/master/sfdx-source/apex-mocks/main/classes/fflib_ApexMocks.cls) | | [Jun 2016](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/pull/23) (#23) | Class [`fflib_ArgumentCaptor`](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/blob/master/sfdx-source/apex-mocks/main/classes/fflib_ArgumentCaptor.cls) | | [Feb 2016](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/pull/11) (#11) | Class [`fflib_Match`](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/blob/master/sfdx-source/apex-mocks/main/classes/fflib_Match.cls)
Exception: [`fflib_ApexMocks.ApexMocksException`](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/blob/master/sfdx-source/apex-mocks/main/classes/fflib_ApexMocks.cls) | | [Nov 2014](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/pull/2) (#2) | Method [`fflib_ApexMocks.doThrowWhen(Exception, Object)`](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/blob/master/sfdx-source/apex-mocks/main/classes/fflib_ApexMocks.cls) | | [Sep 2014](https://github.com/apex-enterprise-patterns/fflib-apex-common/commit/c7e04db9ccb6ab754a2356bbc363f8bb3d080d3c) | Class [`fflib_ISObjectDomain`](https://github.com/apex-enterprise-patterns/fflib-apex-common/blob/master/sfdx-source/apex-common/main/classes/fflib_ISObjectDomain.cls) | | [Jun 2014](https://github.com/apex-enterprise-patterns/fflib-apex-common/commit/ec45ada13232acd69277daa8c8f3dacd2d1e29df) | Class [`fflib_SObjectDescribe`](https://github.com/apex-enterprise-patterns/fflib-apex-common/blob/master/sfdx-source/apex-common/main/classes/fflib_SObjectDescribe.cls), [`fflib_SecurityUtils`](https://github.com/apex-enterprise-patterns/fflib-apex-common/blob/master/sfdx-source/apex-common/main/classes/fflib_SecurityUtils.cls) | | [May 2014](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/commit/c08b3a7113ccc05a910785403b378190efdfb81b) | Class [`fflib_ApexMocks`](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/blob/master/sfdx-source/apex-mocks/main/classes/fflib_ApexMocks.cls), [`fflib_MethodReturnValue`](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/blob/master/sfdx-source/apex-mocks/main/classes/fflib_MethodReturnValue.cls), [`fflib_IDGenerator`](https://github.com/apex-enterprise-patterns/fflib-apex-mocks/blob/master/sfdx-source/apex-mocks/main/classes/fflib_IDGenerator.cls) | While pull request #300 introduced more classes, these aren't referenced by D'fflib and therefore not mandatory. For completeness of the functionality it is recommended to apply. Though if you have local customisations to `fflib_SObjectDomain`, those don't need to be overwritten for D'fflib to compile and function.
*** ### Upgrade [#upgrade] Upgrading follows the same path as a migration, though shorter: the framework is already in place, so the focus is on breaking changes, your customisations and a validated roll-out. **Recap** * Check which D'fflib version you have installed (`Setup > Installed Packages`). * List your projects' known customisations of (D')fflib classes. **Review Release Notes** * Review the [release notes](https://github.com/deloitte-engineering/dfflib-code/releases) of every version between your current and the target version. * For breaking changes, determine impact on your implementation * For new features, consider whether you might benefit, and plan the migration effort. * For API version updates, check the [known migration issues](#known-migration-issues). **Review checksum** * At the bottom of the release notes you can find the checksum to list all files changed in that release. * For project customisations, check whether still relevant and overrides are needed. * For manual distribution, determine per `fflib-apex-common` and `fflib-apex-mocks` file change whether you'd like to adopt. * For BYO distribution, review the [prerequisites table](#byo-prerequisites) to validate whether new prerequisites require adoption. * Validate whether all Apex classes compile and unit tests pass. If not, resolve them, or document which fail. * Follow above [Fresh install](#fresh-install) steps in a separate or DEV sandbox to update to a newer D'fflib version. * Installing the package overwrites your customisations. Retrieve the new class version from the org, re-apply the customisation and deploy it to override. * Never redeploy the previous customised file: it can revert the changes of the new release and cause compilation errors. * A minor change is needed to force a delta for your CI/CD to enforce your customisations. Validate whether your enrichment could benefit others. If so, [let us know](/dfflib/docs/faq#contributing-improvements-new-features). * Compile all classes and run all unit tests. * Adopt the new features identified in step 1, based on capacity and priorities. *** ## Next steps [#next-steps] Installing the package itself won't change code quality. You'll need to start absorbing and applying the patterns to realise the benefits. Read more on a suggested and phased approach. Regardless of the starting point, developers should be trained and enabled to ensure they can maximise the benefits of D'fflib, and thus ensure scalable and maintainable Salesforce features. Questions or support needed for installation, adoption or application? Like understanding how you can maximise the framework benefits? Spotted a bug, have a question or want to request a feature? Log an issue in the GitHub repository. Questions on installation, relevancy and applicability for your project. *** ### AI-assisted development [#ai-assisted-development] * AI code assistants can read this documentation website directly. To give them the most accurate D'fflib context, we generate: llms.txt and llms-full.txt . A dedicated (D')fflib AI Skill is being prepared, to recommend and apply the best fitting layer, help with adopting D'fflib features and refactor legacy code. Unfortunately, stress-testing and validation is consuming more time than planned. Expected by end of November. --- # Adoption URL: /dfflib/docs/how/adoption/ Apply D'fflib gradually in your codebase and enable your team: a recommended layer sequence, refactoring decisions, team learning and AI-assisted development. Installing the package itself won't change code quality. This page helps you **absorb and apply the patterns** to realise the benefits. Not installed yet? Start with [Get started](/dfflib/docs/how/get-started). ## Application [#application] Once D'fflib is installed, there are multiple ways to start applying (and benefiting from) the framework. When your team is fully familiar with the framework and starting a greenfield project, you can simply enforce it from day one. In most situations, however, a gradual adoption is more practical: it allows the team to get familiar without disrupting productivity or overhauling an existing codebase all at once. ### Incremental application [#incremental-application] Aside from the structuring of code, the biggest benefit of fflib comes from the ability to mock methods in unit tests and reduce deployment time significantly. To realise these benefits, prioritise moving database interactions (queries and DML) onto (D')fflib first so these features can be leveraged. Based on experience, we recommend starting with a specific layer sequence, and tailor the guidelines/enforcement based on your projects' code and team experience. Start with minor adjustments that don't heavily depend on the framework signatures. This allows you to make things tangible, gain experience and realise benefits quickly. Note that this is a recommendation and not the only way. The right approach differs by project and team context. Regardless of the approach, **consistency is key**. Once you decide on an approach, including naming conventions and standards, commit to it and make sure all developers apply it consistently. #### Layer adoption sequence [#layer-adoption-sequence] **[Selectors](/dfflib/docs/how/selectors)**\ Start by moving queries to selectors as this is the simplest step, prepares for future usage and is easy to track (number of inline queries). **[Domain statics](/dfflib/docs/how/domains)**\ Move SObject-specific statics (like statuses or picklist values) to the domain layer to start deduplicating and centralising them. Small SObject-specific utility methods can also be gradually moved here. **[Unit of Work](/dfflib/docs/how/unit-of-work)**\ Move DML operations to the Unit of Work, enabling you to start mocking unit tests, avoid test data insertion and reduce deployment times. This also simplifies complex (relational) DML operations, ensures transaction management is always applied (removing repetitive duplicate code), and guarantees only one DML interaction per SObject per transaction. **[Test Factory](/dfflib/docs/how/testing-mocking)**\ Move (local) test data creation to Test Factories to enable reuse and centralise test data construction. **[Triggers](/dfflib/docs/how/trigger-handlers)**\ Move each new trigger to the metadata-driven trigger handler, enabling efficient unit tests and streamlined, clear transaction management. **[Entrypoints](/dfflib/docs/how/entrypoints)**\ Clearly separate backend initiations into dedicated entry layer classes (Batch, LWC/Aura/VF controllers, Flows, Queueable, etc.). Avoid any business logic: they solely own the invocation of other layers, transaction management and possible mutations/translations of payloads and texts. **Business logic to [Domains](/dfflib/docs/how/domains) and [Services](/dfflib/docs/how/services)**\ Move all business logic to either Domains or Services depending on their scope, focusing on separation of concerns, deduplication and maintainability. #### Code refactoring guidelines [#code-refactoring-guidelines] To help set expectations and guide the adoption process, the following flowchart outlines the recommended approach based on developer familiarity and the state of the Salesforce org. *** ## Adoption & learning [#adoption--learning] Regardless of the starting point, **developers should be trained and enabled** to maximise the benefits of (D')fflib, and thus ensure a sustainable and maintainable Salesforce implementation. Plan learning, support and championship consciously. Below is a set of recommended sequential steps you can consider when planning adoption and learning of (D')fflib within the team. **Appoint Champions**\ It helps to designate experienced team members as champions who can pave the path, guide others, answer questions, and ensure consistent application of (D')fflib principles across the project. **Raise developer awareness**\ Ensure the team members understand the purpose and benefits. Understanding the high-level concepts of (D')fflib will help them to be motivated to learn and apply. **Build framework knowledge**\ Host training or knowledge sharing sessions to build a solid understanding of the framework among team members. Start with the basics, including its layers and core principles of (D')fflib. Followed by applying per layer. **Learning by doing**\ Start with small, incremental tasks to apply the framework in practice. Supported by the Champions, this hands-on experience helps reinforce learning and build confidence (and often enthusiasm) among team members. **Embrace AI support**\ Despite the importance of proper understanding, AI support can accelerate learning and application by providing context-aware suggestions, code snippets, and guidance aligned with (D')fflib principles. Our [AI skill and LLMs.txt](/dfflib/docs/how/get-started/#ai-assisted-development) might help the team get up to speed faster. **Evaluate periodically**\ It's important to evaluate with the team on their progress and satisfaction, and adjust learning, adoption and application strategies accordingly. **Provide ongoing support**\ Establish channels for continuous support, such as regular Q\&A sessions, documentation updates, and peer reviews, to help team members overcome challenges and reinforce best practices. **Set clear priorities with (business) stakeholders**\ Adopting a new framework consumes time, but it is a valuable investment for the long-term success of the project. It's crucial to, upfront, align with stakeholders on the priorities and [expected benefits](/dfflib/docs/why/business-benefits). This enables the team with sufficient time to learn, grow and mature. **Define realistic milestones**\ Together with the team, define clear milestones or objectives, both on individual level of proficiency, but also on tangible code metrics. For example, 80% of queries migrated to selectors, more code delivered in (D')fflib-structured classes than legacy code or full unit test runtimes reduced by 30%. This can help to create some motivation and purpose for the team, as success becomes tangible and measurable. Ensure to celebrate success, and also define clear guidelines when the 'investment' becomes the new standard. Is your team stuck or facing challenges? We're happy to [support](/dfflib/docs/how/support), with e.g. tailored trainings or a maturity assessment that help your team take the next steps. ## Frequently Asked Questions [#frequently-asked-questions] For questions on installation, relevancy and applicability for your project, [→ visit the FAQ page](/dfflib/docs/faq). --- # Layers explained URL: /dfflib/docs/how/overview/ The entry point for HOW articles, describing the different (D')fflib layers, their responsibilities and interactions; and introducing the Room Booking use-case which is used across all code examples in the layer-specific articles. { /* Prepare Icon shortcuts for the invocation matrix table */ } { /* Prepare Tooltip content for the invocation matrix table */ } ## (D')fflib layers [#dfflib-layers] With the publication of `fflib` in 2014, four main layers were introduced: *Domains*, *Selectors*, *Services*, and the *Unit of Work*. With D'fflib we formalise a fifth layer: *Entrypoints*. Each layer has its own role, responsibilities and interactions, allowing you to separate concerns and create maintainable and scalable codebases, so everyone can easily deduce where specific logic should be placed and how it should be called. The table below lists the layers and frameworks in D'fflib, their defined responsibilities and the link to the detailed articles on how to properly leverage and apply such layer. | Layer | Responsibilities | Documentation | | ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | | Domain | SObject-specific constants, business logic, and trigger orchestration | [→ HOW](/dfflib/docs/how/domains) | | Entry | Bridges front-end and platform automations to core layers.
Invoking, orchestrating and translating different contexts | [→ HOW](/dfflib/docs/how/entrypoints) | | Selector | SObject-specific SOQL queries. Centralised, reusable, and security-adopted | [→ HOW](/dfflib/docs/how/selectors) | | Service | Reusable cross-SObject business operation or functionality (like integrations) | [→ HOW](/dfflib/docs/how/services) | | Unit of Work | Database interaction ledger to simplify registration, relationships and default handling of transactions and fallbacks | [→ HOW](/dfflib/docs/how/unit-of-work) | Additionally, D'fflib includes `fflib-apex-mocks`, a Test Data Builder Framework and a Trigger Handler Framework. | Framework | Responsibilities | Documentation | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | | Test with mocks | Enables to isolate test methods to their single-responsibility. Mocking consumed layers, keep tests understandable, and much faster | [→ HOW](/dfflib/docs/how/testing-mocking) | | Trigger Handlers | Metadata driven handlers to allow bulkified and understandable trigger logic | [→ HOW](/dfflib/docs/how/trigger-handlers) | *** ### Layer interactions [#layer-interactions] Simply put, all code related logic in Salesforce can be brought back to: * **Platform initiators**\ Salesforce automations that trigger internal code, like incoming APIs, user actions (e.g. Quick Action or LWC wire) and automations (Flow/Apex) either triggered by time or record. * **Entry layer**\ Connecting end-users with the backend. Orchestrating calls into the core layers, not containing any business processes, but managing the transactions and errors, and converting payloads and exceptions to initiator suited formats. Like `RestResource`, `Batchable`, `Queueable` and `Schedulable` classes, `Invocable` methods, Trigger Handlers, and Controllers for LWC, Aura or Visualforce. * **Core layers** (Domains, Selectors, Services and Unit of Work)\ 'Passively' invoked layers which should be caller-agnostic as they're unaware of the class and context that invoked them, nor what context it runs in. Thus throwing Exceptions instead of end-user tailored messages. Any business logic is expected to be in one of these classes, and designed for re-use. ### Invocation matrix [#invocation-matrix] To help understand and validate the correctness of layer selection, and avoid deep-circular dependencies between layers, the architecturally and best-practice-based interactions between layers are summarised below: | Caller to callee | Entry | Domain | Selector | Service | Unit of Work | | ---------------------------------------------- | :------------------------------: | :----------------------------------------: | :--------------------------------------: | :----------------------------------------: | :----------------------------------------: | | **Entry** → | | | | | | | **Domain** → | | | | | | | **Selector** → | | | | | | | **Service** → | | | | | | | **Unit of Work** → | | | | | | Hover over the icons for reasoning or examples: (allowed), (with caution) and (not applicable). *** ### Domain vs. Service ambiguity [#domain-vs-service-ambiguity] By definition the ruling is rather simple: * **Domains** contain SObject-specific constants and logic, and house the Trigger Handlers, * **Services** contain cross-SObject business logic. However, in practice the line blurs. Logic that touches one SObject today might touch multiple tomorrow; and Domains can become less maintainable due to the rapid growth housing both SObject business logic and trigger handlers. To support you in discussing the right layer for a specific SObject process next time, find the below suggestions: Multiple Services per object or process can be quite a robust setup. `SRV_OpportunityRenewal`, `SRV_OpportunityMACD`, and `SRV_OpportunityValidation` can all live alongside a lean `DOM_Opportunities`, where each Service owns one focused, reusable and scalable process. (D')fflib thus doesn't enforce a binary cut. However, it gives the vocabulary for the team conversation. Two reasonable engineers on the same team can draw the line differently. It is important to agree on a convention early, document and adhere to it, and evaluate as the codebase grows. In the end, the essence of the Apex Enterprise Design Patterns is to aim for maintainable, scalable and testable codebases, and this should be kept in mind in any future ambiguous layer-design discussion. *** ## Code examples use-case: Room booking system [#code-examples-use-case-room-booking-system] Throughout the HOW articles, a Room Booking system is used as a running example. The model is intentionally simple: a `Room__c` represents a physical location, a `Contact` represents the person making the booking, and a `RoomReservation__c` junction object ties them together with a date range and a status field. Every code snippet in the per-layer HOW articles is drawn from this same data model so that examples build on each other rather than introducing new context with every article. Where this model allows examples to be simple and understandable, while enabling us to showcase most of the framework's strengths, such as: * Allow guest-user vs. internal-user flows to leverage the same Selectors, while the invoking class **distinguishes the user mode via Database Context** * Upon reservation, the postal code is validated via a **REST API**, * the closest available room is suggested via a **geolocation query** * Junction record **relationship registration** via Unit of Work and Selector inclusion of **relationship fields** and **subselects** * **Aggregate Result queries** to check for existing reservations and calculate total revenue per room * A **simple trigger** to calculate the total price based on nightly rate and number of nights, or prevent Room deactivation when there are active future reservations --- # Domains URL: /dfflib/docs/how/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. This article has the single responsibility to elaborate on the Domain layer, initiation and usage.\ [→ Click here to visit the trigger handlers documentation](/dfflib/docs/how/trigger-handlers), to learn how those can be registered and implemented. ## Characteristics [#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 [#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 [#interactions] | Interaction | Layers | | ----------- | ------------------------------ | | Called by | Entrypoints, Services, Trigger | | Calling | Selectors, Unit of Work | ### Rules [#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](/dfflib/docs/how/trigger-handlers).* *** ## Initiation [#initiation] ### How to call [#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: ```apex // 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: ```apex title="CTRL_RoomReservations.cls" repo="classes/CTRL_RoomReservations.cls" DOM_RoomReservations.newInstance( reservations ).validateRecords(); ``` ### Class boilerplate [#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. ```apex title="DOM_RoomReservations.cls" repo="classes/DOM_RoomReservations.cls" public with sharing class DOM_RoomReservations extends dfflib_SObjectDomain{ // Statics ... // Constructor accepting list of records public DOM_RoomReservations( List 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 ); can be added, but be aware of the query performed internally public static DOM_RoomReservations newInstance(){ return newInstance( new List() ); } public static DOM_RoomReservations newInstance( List 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 sObjectList ){ return new DOM_RoomReservations( ( List ) 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](/dfflib/docs/what/accelerators-utilities#fflib_sobjects). * 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`, instead of `List`), 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. ```apex ( ( DOM_RoomReservations ) dfflib.domain.newInstance( reservations ) ).validateRecords(); ``` ### Metadata registration [#metadata-registration] Register the Domain in `Dfflib_Domain_Config__mdt` so the framework can resolve it via `dfflib.domain.newInstance()` and the trigger handler. | Field | Purpose | Example | | ------------------------ | ----------------------------------------------------------------------------------------------------- | ---------------------------------- | | `MasterLabel` | Label of the mdt record. Shown in Setup | `Room Reservation` | | `DeveloperName` | Unique API name of the record. Doesn't allow duplicate (`___`) thus write custom SObjectTypes as `_c` | `RoomReservation_c` | | `SObjectType__c` | API name of the SObject | `RoomReservation__c` | | `Implementation_Type__c` | Constructor inner class path | `DOM_RoomReservations.Constructor` | | `Is_Trigger_Disabled__c` | Intended to switch off all trigger handling for this SObject (*not yet effective*) | `false` | *** ## Code examples [#code-examples] ### Constants [#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. ```apex title="DOM_Rooms.cls" repo="classes/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 [#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. ```apex title="DOM_RoomReservations.cls" repo="classes/DOM_RoomReservations.cls#L48" // DOM_RoomReservations.newInstance( records ).validateRecords(); public void validateRecords(){ List reservations = ( List ) 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 [#inherited-collection-utilities] Instead of hand-written loops, business methods can leverage [the utilities](/dfflib/docs/what/accelerators-utilities#fflib_sobjects) inherited from `fflib_SObjects`. Most of them are `protected`, so they are available inside your Domain methods. | Need | Inherited utility | | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Collect Ids, or Ids of a parent | `getRecordIds()`, `getParentIdFieldValues( 'Room__r.Location__c' )`, `getIdFieldValues( field [, includeNulls] )` | | Collect other field values | `getFieldValues( field )`, `getStringFieldValues( field )` | | Narrow the scope on field values | `getRecordsByFieldValue( field, value )`, `getRecordsByFieldValues( field, values )` | | Find (in)complete records | `getRecordsWithBlankFieldValues( fields )`, `getRecordsWithAllBlankFieldValues( fields )`, `getRecordsWithNotBlankFieldValues( fields )`, `getRecordsWithAllNotBlankFieldValues( fields )` | | Group records per key | `groupRecordsByFieldValue( field )` | | Bulk update or reset fields | `setFieldValue( field, value )`, `setFieldValueByMap( fieldToCheck, fieldToUpdate, values )`, `clearField( field )`, `clearFields( fields )` | ```apex // Ids of the booked rooms, excluding nulls, e.g. to pass to SEL_Rooms public Set getRoomIds(){ return getIdFieldValues( RoomReservation__c.Room__c, false ); } // Records of the scope that are still open public List getOpenReservations(){ return ( List ) getRecordsByFieldValues( RoomReservation__c.Status__c, new Set( STATUSES_OPEN ) ); } // Reservations per Contact, e.g. for reporting or notifications public Map> 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](/dfflib/docs/what/accelerators-utilities#fflib_sobjects). *** ## Testing a Domain [#testing-a-domain] See [Testing & Mocking](/dfflib/docs/how/testing-mocking) for the full testing patterns.\ Testing trigger handlers, including the `runHandler()` shortcut, is covered in [Triggers & Handlers](/dfflib/docs/how/trigger-handlers#testing-a-trigger). 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](/dfflib/docs/what/test-factory-builder-framework) in the respective Domain test class, but that is project-specific. ```apex title="DOM_RoomReservationsTest.cls" repo="classes/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{ 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 [#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](/dfflib/docs/how/get-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()` D'fflib Domain fflib-apex-common Domain ```apex // [!code word:dfflib] public with sharing class DOM_Rooms extends dfflib_SObjectDomain{ public static DOM_Rooms newInstance( List sObjectList ){ return ( DOM_Rooms ) dfflib.domain.newInstance( sObjectList ); } } ``` ```apex public with sharing class DOM_Rooms extends fflib_SObjectDomain{ public static DOM_Rooms newInstance( List 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](/dfflib/docs/how/trigger-handlers#migration-steps). 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. ```apex public DOM_Rooms( List 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](#inherited-collection-utilities). --- # Entrypoints URL: /dfflib/docs/how/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 [#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 [#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 [#interactions] | Interaction | Layers | | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | Invoked by | Platform and external callers: LWC, Flow, Visualforce, Scheduler, `Database.executeBatch()`, `System.enqueueJob()`. Never by other Apex classes | | Calling | Selectors, Domains, Services, Unit of Work | ### Entry point types [#entry-point-types] | Entry Point Type | Annotation / Interface | Class prefix | | -------------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Agent & Flow actions | `@InvocableMethod` | `Flow_` | | Aura & LWC methods | `@AuraEnabled` | `CTRL_` | | Batch | `Database.Batchable` | `Batch_` | | Queueable | `Queueable` | `Queue_` | | Scheduled | `Schedulable` | `Sched_` | | Visualforce | (standard public class) | `CTRL_` | Incoming APIs (`@RestResource`) follow Service naming (`SRVi_`) despite being a system entry. ### Rules [#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`, `List` or `List` 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 [#initiation] ### How to call [#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 [#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 [#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) [#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`](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/CTRL_RoomReservations.cls) exposes three methods: * [`getAvailableRooms`](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/CTRL_RoomReservations.cls#L26) for data retrieval * [`createReservations`](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/CTRL_RoomReservations.cls#L59) for data insertion and [partial success](/dfflib/docs/how/unit-of-work#saveresults-) handling * [`cancelReservations`](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/CTRL_RoomReservations.cls#L109) for data updates Each method validates its input, delegates to the appropriate service or domain and returns a standardised [`SRV_Response.Response`](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/SRV_Response.cls) so the front-end developers can consistently handle responses. For this, one [`errorResponse`](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/CTRL_RoomReservations.cls#L146) helper is set up to centralise exception translation. getAvailableRooms createReservations cancelReservations errorResponse ```apex title="CTRL_RoomReservations.cls" repo="classes/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 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 ); } } } ``` ```apex title="CTRL_RoomReservations.cls" repo="classes/CTRL_RoomReservations.cls" public with sharing class CTRL_RoomReservations{ // Data-insertion: validate -> UoW -> register -> commit -> respond @AuraEnabled public static SRV_Response.Response createReservations( List 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 errors = new Map(); // ... 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 ); } } } ``` ```apex title="CTRL_RoomReservations.cls" repo="classes/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 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 ); } } } ``` ```apex title="CTRL_RoomReservations.cls" repo="classes/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`; use `List` 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. ```apex title="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 [#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`) 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. ```apex title="Flow_AddressLookup.cls" repo="classes/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 lookupAddresses( List requests ){ // Construct List of Response objects corresponding to same sequence as received requests List responses = new List(); // 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`, 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-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. Batch Queueable Schedulable ```apex public with sharing class Batch_ConfirmPendingReservations implements Database.Batchable{ // 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 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 } } ``` ```apex public with sharing class Queue_ConfirmReservations implements Queueable { private Set recordIds; // Pass Ids, not SObjects: data may be stale by the time it runs public Queue_ConfirmReservations( Set 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 } } } ``` ```apex title="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, 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. 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 [#testing-an-entrypoint] See the [Testing & Mocking](/dfflib/docs/how/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`](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/CTRL_RoomReservationsTest.cls) and [`Flow_AddressLookupTest`](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/Flow_AddressLookupTest.cls) cover all happy and unhappy flows, each thoroughly focusing on the responsibilities of the tested method only. Happy path DML exception Partial failure stubResponseService() ```apex title="CTRL_RoomReservationsTest.cls" repo="classes/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 reservations = new List{ 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 ); } ``` ```apex title="CTRL_RoomReservationsTest.cls" repo="classes/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{ reservation } ); // Then ( ( SRV_Response ) mocks.verify( m_srvResponse, 1 ) ).setResponse( SRV_Response.TYPES.DML_ERROR, exceptionMessage ); } ``` ```apex title="CTRL_RoomReservationsTest.cls" repo="classes/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 reservations = new List{ ( RoomReservation__c ) TestFactory.aRoomReservation().asDefault().mock(), ( RoomReservation__c ) TestFactory.aRoomReservation().asDefault().mock() }; String dmlMessage = 'The room is already booked for these dates'; List saveResults = new List{ 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{ 1 => dmlMessage } ); } ``` ```apex title="CTRL_RoomReservationsTest.cls" repo="classes/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 [#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. --- # Selectors URL: /dfflib/docs/how/selectors/ Step-by-step guide on how to set up and interact with a Selector, maximise the functions and benefits, while being aware of edge cases and D'fflib specific functionalities. ## Characteristics [#characteristics] A Selector is the one place that centralises and knows how to read a single SObject: which fields, which filters, which security context. It answers "which records?" without knowing who asked or why. Think of a librarian: it fetches exactly what you request and never decides what you do with it. ### Responsibilities [#responsibilities] Selectors implement the *Selector/Repository pattern*, with the main responsibilities to: Centralise construction and execution of all SOQL queries for one SObject. Centralise and standardise security enforcement. Enable mockable queries in unit tests. With the `dfflib_Database` proxy layer , D'fflib separates the concerns. Where originally, Selectors also performed the effective query, this has now been separated. Making Selectors more caller-agnostic, since methods can be reused across different context-needs. By allowing the calling class to define the Context, Selectors no longer need to differentiate, including the repetitive `withSharing` Booleans and inner-`WithoutSharing`-classes. * Selectors focus on capturing 'how' to retrieve (security settings), * QueryFactories focus on 'what' to retrieve (fields and conditions), * Database proxies interact with the database. Note, SOSL queries aren't natively supported in (D')fflib, as one can span multiple SObject types, and therefore don't fit in Selectors. If you need a SOSL query, you can consider a SOSL Service class to enable mocking. Only when the SOSL is, and will remain, limited to one SObjectType, you're free to place this in the Selector for that specific SObjectType. ### Interactions [#interactions] | Interaction | Layers | | ----------- | --------------------------------------------------- | | Called by | Entrypoints, Domains, Services and Trigger Handlers | | Calling | N/A | By design, there should be no need for a Selector to call another layer, to meet its responsibilities. Other Selectors can be referenced for subselects, but those don't require a selector initiation. Domains and Services contain business logic and should not be called from a Selector, as that would violate the separation of concerns. Due to this setup Selector methods should be caller agnostic and not assume any context of the caller. This implies the conversion from a `List` to a wrapper class should be performed in the calling class and not in the Selector. ### Rules [#rules] * Methods should be caller agnostic and not assume any context of the caller. * Methods should be bulkified and accept a `Set` or `List` as input. * Methods should return a caller-agnostic `List` and not a wrapper class. In edge-cases one could opt to return `SObject` to centralise the `.isEmpty()` or `.size() == 1` check, though an Exception should be thrown when multiple or no records are found. * Method names should be descriptive and indicate the purpose of the query, e.g. `selectByRoomId` or `selectByStatusAndDateRange`. *** ## Initiation [#initiation] ### How to call [#how-to-call] Selectors are always instantiated via the (class-specific) static `newInstance()` factory method. For D'fflib we highly recommend to always pass the `dfflib_Database.Context` to the factory method, as this enables the caller to control the query security context. ```apex // Always pass the Database Context — the caller decides security, not the method List reservations = SEL_RoomReservations .newInstance( dfflib_Database.Context.FULL ) .selectByRoomIds( roomIds ); ``` [→ Full table of Database Context options](/dfflib/docs/what/database-context#database-context-enum) ### Class boilerplate [#class-boilerplate] Below snippet shows the boilerplate code for a Selector class, extending the framework-base-class and implementing the required `newInstance()`, `getSObjectType()` and `getSObjectFieldList()` methods. `getRelatedFieldSet()` is an optional method to auto-include parent fields to selector methods. ```apex title="SEL_RoomReservations.cls" repo="classes/SEL_RoomReservations.cls" // Comments are only to elaborate and don't follow JavaDoc standard, so should be removed when copying. public with sharing class SEL_RoomReservations extends dfflib_SObjectSelector{ // Factory method to instantiate the selector public static SEL_RoomReservations newInstance( dfflib_Database.Context ctx ){ return ( SEL_RoomReservations ) dfflib.selector.newInstance( RoomReservation__c.SObjectType, ctx ); } // Returns the SObject type this selector operates on public override Schema.SObjectType getSObjectType(){ return RoomReservation__c.SObjectType; } // Base fields always included in every query from this selector public override List getSObjectFieldList(){ return new List{ RoomReservation__c.Id, RoomReservation__c.Contact__c, RoomReservation__c.Room__c, RoomReservation__c.Status__c }; } // optional, auto-include parent fields without subselect public override Set getRelatedFieldSet(){ return new Set{ 'Room__r.Name', 'Room__r.Capacity__c' }; } } ``` * There is no framework need to construct an interface like `ISelector`. Examples including such, predate the Apex Stub API to enable mocking. The framework factory (`dfflib.selector`) will: 1. Check whether a mock-instance was set and return if available 2. Retrieve the related `Dfflib_Selector_Config__mdt` metadata 3. Instantiate the Selector class with the retrieved configuration. 4. Return the constructed Selector class-instance. Theoretically, it is possible to call `dfflib.selector.newInstance()` directly to avoid the static `newInstance()` boilerplate in your Selector. However, you'll need to cast its generic `dfflib_SObjectSelector` result and repeat the SObjectType argument that the Selector class would otherwise define centrally. Regardless of choice, the recommendation is to be consistent throughout your codebase. ```apex SEL_RoomReservations selectorDirect = ( SEL_RoomReservations ) dfflib.selector.newInstance( RoomReservation__c.SObjectType, dfflib_Database.Context.FULL ); ``` ### Metadata registration [#metadata-registration] To ensure the `newInstance()` factory method resolves the correct class, the Selector must be registered in the `Dfflib_Selector_Config__mdt` custom metadata type . With the right AI skills, this metadata file can be automatically generated, else ensure to set the below values: | Field | Purpose | Example | | ------------------------ | ----------------------------------------------------------------------------------------------------- | ---------------------- | | `MasterLabel` | Label of the mdt record. Shown in Setup | `Room Reservation` | | `DeveloperName` | Unique API name of the record. Doesn't allow duplicate (`___`) thus write custom SObjectTypes as `_c` | `RoomReservation_c` | | `SObjectType__c` | API name of the SObject | `RoomReservation__c` | | `Implementation_Type__c` | Class implementing the Selector | `SEL_RoomReservations` | Note, this registers the Selector to the SObjectType, implying that - for now - it's not possible to have multiple Selectors for the same SObjectType. *** ## Standard methods [#standard-methods] Selector methods follow a consistent pattern: 1. Initiate a QueryFactory 2. Set the desired fields, conditions, grouping etc. 3. Return the database response It's a public method that returns a `List` and optionally accepts input parameters for dynamic conditions, which should always be fit for future. ```apex public List selectByRoomIds( Set roomIds ){ dfflib_QueryFactory qf = newQueryFactory(); qf.setCondition( 'Room__c IN :roomIds' ); return this.executeQuery( qf, new Map{ 'roomIds' => roomIds } ); // qf.toSOQL(): // SELECT Id, Name, Room__c, Status__c // FROM RoomReservation__c // WHERE Room__c IN :roomIds ORDER BY Name } ``` ### 1. Initiate query factory [#1-initiate-query-factory] The framework provides multiple options to simplify initiation of a `dfflib_QueryFactory` via the Selector's `newQueryFactory()` method. Enabling easy control whether or not selector-defined-fields should be included in that particular method | Signature | `includeSelectorFields` | `includeRelatedFieldSetFields` | When to use | | --------------------------------------------------- | ----------------------- | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | | `newQueryFactory()` | `true` | `false` | Default/Recommended, to auto-include configured fields | | `newQueryFactory( false )` | `false` | `false` | Full control on included fields, excluding standard set. E.g. for aggregate queries or access-restricted users (Community Users) | | `newQueryFactory( true, true )` | `true` | `true` | When you also need parent fields from `getRelatedFieldSet()` (e.g. `Room__r.Name`) | With above signatures the original security parameters (`assertCRUD` / `enforceFLS`) will always default to `null`, which causes code to skip the original logic as this now is governed by `dfflib_Database.Context` which is set upon selector construction, not per query call. Note, original signatures still exist for backward compatibility, but are recommended to only be used in existing code or unique edge cases. | Signature | assertCRUD | enforceFLS | includeSelectorFields | includeRelatedFieldSetFields | | ---------------------------------------------------------------------------------------------- | ---------- | ---------- | --------------------- | ---------------------------- | | newQueryFactory( assertCRUD, enforceFLS, includeSelectorFields ) | caller | caller | caller | false | | newQueryFactory( assertCRUD, enforceFLS, includeSelectorFields, includeRelatedFieldSetFields ) | caller | caller | caller | caller | | newQueryFactory( assertCRUD, enforceFLS, includeSelectorFields, dataAccess ) | caller | caller | caller | false | * `assertCRUD`: When true, `objType.getDescribe().isAccessible()` is validated before querying, optionally throwing a `dfflib_SObjectDomain.DomainException`. * `enforceFLS`: When true, performs `objType.getDescribe().getField( fieldName ).getDescribe().isAccessible()` for each field, optionally throwing an `fflib_SecurityUtils.FlsException` when running user has no access. * Optionally `setDataAccess(DataAccess)` could be set on the selector which will override the default `enforceFLS` based on the enum-value (`USER_MODE` or `SYSTEM_MODE`). **Legacy `DataAccess` mapping**\ A legacy `DataAccess` value resolves to a [`dfflib_Database.Context`](/dfflib/docs/what/database-context#database-context-enum): | `DataAccess` | `dfflib_Database.Context` | | ------------- | ------------------------- | | `LEGACY` | `INHERIT` | | `USER_MODE` | `FULL` | | `SYSTEM_MODE` | `INHERIT` | fflib applies `WITH SYSTEM_MODE`, which skips CRUD/FLS, and leaves record sharing to the sharing keyword of the selector class that runs the query. `INHERIT` resolves the same way, through the `inherited sharing` query proxy. One difference from fflib: a `without sharing` selector calling an inherited base method (e.g. `selectSObjectsById()`) now runs without sharing, where fflib's `with sharing` base class applied sharing. Selectors that rely on seeing all records should pass `Context.NONE` explicitly. ### 2. Set query context [#2-set-query-context] A SOQL query typically consists of three parts: SELECT (fields & subselects), WHERE conditions and ORDER BY. Below sections introduce the framework methods relevant per part of the query and how to properly apply them. Lesser common queries are detailed in the [Advanced section](#advanced-methods) like aggregate queries with GROUP BY and HAVING, or queries with FOR etc. #### SELECT fields [#select-fields] When you need additional fields than listed in `getSObjectFieldList()`, you can call: * `selectFields()` or `selectField()`\ which both accept `SObjectField` and `String` field references, and the plural method accepts both Lists and Sets. `SObjectField` tokens are preferred, given their compilation validation which prevents against unconscious deletions. For the plural method Sets are preferred, given their unique-characteristics. ```apex title="SEL_RoomReservations.selectByRoomId" repo="classes/SEL_RoomReservations.cls" dfflib_QueryFactory qf = newQueryFactory( false ); qf.selectField( RoomReservation__c.Room__c ); qf.selectFields( new List{ RoomReservation__c.CheckInDate__c, RoomReservation__c.CheckOutDate__c } ); // SELECT Room__c, CheckInDate__c, CheckOutDate__c FROM RoomReservation__c ``` `String` field references enable inclusion of parent-object-fields or SOQL aggregate functions with aliases. ```apex title="SEL_RoomReservations.selectOpenCountPerRoomId" repo="classes/SEL_RoomReservations.cls" qf.selectField( 'Contact__r.Name' ); // cross-object (parent field) qf.selectFields( new Set{ 'COUNT( Id ) numOpenReservations' } ); // aggregate function with alias ``` * `selectFieldSet( Schema.FieldSet )`\ If the environment leverages FieldSets, these can be easily included to queries. Given the usage of Sets in QueryFactory, there is no need to write logic to prevent duplicate field inclusions. *** #### SELECT subselects [#select-subselects] To reduce the number of queries, SOQL allows you to query child-records while retrieving the parent record. In one query it's thus possible to query the record itself, fields from a parent record and some child records. E.g. fetching a Contact with parent Account segmentation and all future RoomReservation__c records. The `fflib` framework supports two ways to configure subselects, for different use-cases and preferences. * `query.subselectQuery( relationship )`\ Accepts either the `String` relationship name or `Schema.ChildRelationship`.\ Returns a blank `dfflib_QueryFactory` based on the relationship name, only inheriting parents' FLS and `dfflib_Database.Context` setup. This gives more control on the constructed subselect, and allows subselects for SObjectTypes with no Selector class (yet). * `new SEL_RoomReservations().addQueryFactorySubselect( parentQueryFactory, relationshipName )`\ Accepts the parent QueryFactory and `String` relationship name. Returns a (default) configured `dfflib_QueryFactory`, calling `configureQueryFactory()` which automatically includes `getSObjectFieldList()` fields, default `ORDER BY` and security settings based on inherited values from `dfflib_SObjectSelector`. This puts the selector class as the source of truth, which does imply that if any new field is added to the selector, it will automatically be added to all such subselect queries. This method does call `subselectQuery()` internally, implying there is no distinction in e.g. the mock-possibilities. ```apex title="SEL_Rooms" dfflib_QueryFactory qf = newQueryFactory( false ); dfflib_QueryFactory subQF = qf.subselectQuery( 'Reservations__r' ); subQF.selectFields( new List{ 'Id', 'Status__c', 'CheckInDate__c' } ); // SELECT Id, // (SELECT id, status__c, checkindate__c FROM Reservations__r) // FROM Room__c ORDER BY Name ASC NULLS FIRST dfflib_QueryFactory qf = newQueryFactory( false ); dfflib_QueryFactory subQF = new SEL_RoomReservations().addQueryFactorySubselect( qf, 'Reservations__r' ); // SELECT Id, // (SELECT id, name, checkindate__c, checkoutdate__c, contact__c, ... FROM Reservations__r ORDER BY Name ASC NULLS FIRST ) // FROM Room__c ORDER BY Name ASC NULLS FIRST ``` Note, for full flexibility `fflib` includes: * `addQueryFactorySubselect(parentQueryFactory, relationshipName, includeSelectorFields)`\ to control whether default fields are included * `addQueryFactorySubselectNoAccessChecks(parentQueryFactory, relationshipName, includeSelectorFields)`\ to allow disabling `assertCRUD` validation in subselect execution This implies that one could realise the exact same query with both approaches: ```apex qf.subselectQuery( 'Reservations__r' ); new SEL_RoomReservations().addQueryFactorySubselectNoAccessChecks( qf, 'Reservations__r', false ).emptyOrdering(); // SELECT Id, (SELECT Id FROM Reservations__r) FROM Room__c ORDER BY Name ASC NULLS FIRST ``` Each SOQL query allows up to 20 subselects, with a limit of 50,000 records for all records (including child-records). Per API 58.0 (Summer '23) and 61.0 (Summer '24), Salesforce loosened the limit of two levels (one subselect) to five levels (record + 4 levels of nested subselect), first for REST and SOAP API calls, then for Apex. *** #### WHERE conditions [#where-conditions] To retrieve only the desired records, it's best practice to define a `WHERE` clause. Due to the endless possibilities, the framework does not enforce a specific structure, but instead expects a single `String` with the full condition. * `setCondition( String )`\ Directly sets the `WHERE` clause, where bind-variables (`:varName`) should be used to mitigate SOQL injections and optimise query plan caching. ```apex title="SEL_RoomReservations.selectByRoomId" repo="classes/SEL_RoomReservations.cls" dfflib_QueryFactory qf = newQueryFactory(); qf.setCondition( 'Room__c IN :roomIds' ); return this.executeQuery( qf, new Map{ 'roomIds' => roomIds } ); // SELECT Id FROM RoomReservation__c WHERE Room__c IN :roomIds ORDER BY Name ``` **Multiple conditions**\ To set multiple conditions, each project can decide their preference for condition construction, as long as there is consistency in the codebase. Our preference is to construct a `List` and combine this with `String.join()`. Based on the 'expensive' nature of String concatenation in Apex, and the ease of adding conditions dynamically to the list before joining. ```apex title="SEL_RoomReservations.selectOpenCountPerRoomId" repo="classes/SEL_RoomReservations.cls" dfflib_QueryFactory qf = newQueryFactory(); List conditions = new List{ 'Room__c IN :roomIds', 'Status__c IN :openStatuses' }; //if( isFutureReservation ){ // conditions.add( 'CheckInDate__c >= :startDate' ); //} qf.setCondition( String.join( conditions, ' AND ' ) ); return this.executeQuery( qf, new Map{ 'roomIds' => roomIds, 'openStatuses' => DOM_RoomReservations.STATUSES_OPEN } ); // SELECT Id FROM RoomReservation__c WHERE Room__c IN :roomIds AND Status__c IN :openStatuses ORDER BY Name ``` **WHERE ... IN (SELECT ...)**\ Relating the previous two sections, the framework fully supports to set a subselect SOQL condition, via the `WHERE ... IN (SELECT ...)` syntax, but doesn't enforce a specific structure, as this is highly dependent on the use-case and project standards. ```apex title="Possible method for Rooms Selector" public List selectRoomsWithFutureReservations( Date startDate ){ dfflib_QueryFactory qf = newQueryFactory(); List conditions = new List{ 'Status__c IN :openStatuses', 'Id IN ( SELECT Room__c FROM RoomReservation__c WHERE CheckInDate__c >= :startDate )', }; qf.setCondition( String.join( conditions, ' AND ' ) ); return this.executeQuery( qf, new Map{ 'startDate' => startDate, 'openStatuses' => DOM_Rooms.STATUSES_OPEN } ); // SELECT Id FROM Room__c WHERE Status__c IN :openStatuses // AND Id IN ( SELECT Room__c FROM RoomReservation__c WHERE CheckInDate__c >= :startDate ) // ORDER BY Name } ``` *** #### ORDER BY [#order-by] For data consistency across sequential query-executions, the QueryFactory applies a default `getOrderBy()`. This is the `Name` field, when available and not encrypted, or `CreatedDate`, and as final fallback `Id`. The SOQL order is kept as a List of `Ordering` instances, default with the first value which is set in `newQueryFactory()`. Therefore, one should be cautious when adding *additional* orderings, and consider the relevant function: * `addOrdering` appends to existing `ORDER BY` (including the default) * `setOrdering` replaces existing orderings (including the default) with a single ordering * `emptyOrdering` clears all orderings, to e.g. prevent SOQL validation errors for `GROUP BY` Each method accepts: * `Schema.SObjectField` (recommended) or `String` field names (for parent-fields and aliases/expressions) * `dfflib_QueryFactory.SortOrder` enum for `ASCENDING` or `DESCENDING` direction * Optional `nullsLast` boolean to explicitly set `NULLS FIRST/LAST`. Default `false`, as per Salesforce default ```apex title="Ordering signature examples" // Appends to existing ORDER BY (RoomReservation__c.Name ASC NULLS FIRST) qf.addOrdering( RoomReservation__c.CheckInDate__c, dfflib_QueryFactory.SortOrder.ASCENDING ); // NULLS FIRST qf.addOrdering( RoomReservation__c.TotalPrice__c, dfflib_QueryFactory.SortOrder.DESCENDING, true ); // NULLS LAST // Replaces existing orderings (including the default) with a single clause qf.setOrdering( RoomReservation__c.Status__c, dfflib_QueryFactory.SortOrder.ASCENDING ); // Removes existing orderings entirely // E.g. avoid SOQL validation error for `GROUP BY` when default Order by field isn't grouped qf.emptyOrdering(); ``` ### 3. Execute query [#3-execute-query] Once the `dfflib_QueryFactory` is configured, specify the execution method that matches the query type. All variants accept either a `dfflib_QueryFactory` instance or a raw SOQL string, with an optional bind-variable map. Ensure the selector methods' return type matches that of the framework's method. It's recommended to put `this.` upfront to indicate the method is inherited from `dfflib_SObjectSelector`. | Method | Returns | When to use | | --------------------------------------- | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | | `executeQuery( qf, bindVars )` | `List` | Standard `SELECT` execution for record-returning methods | | `executeAggregateQuery( qf, bindVars )` | `List` | Queries with `GROUP BY` or aggregate functions. Note, default returns `dfflib_AggregateResult` which can be mocked in unit tests | | `getQueryLocator( qf, bindVars )` | `Database.QueryLocator` | Commonly used in Batch classes to iterate over large data sets | | `getCursor( qf, bindVars )` | `Database.Cursor` | Cursor-based pagination outside Batch | D'fflib provides above four methods to offload the effective `Database.query` operation and with that grant flexibility to control the context the query runs with and thus, unlock mocking in unit tests. Originally, the last statement in a selector method would be `return Database.query( qf.toSOQL() )`, which caused the query to run in the context of the selector class, and required bind-variables to exist on execution. *** ## Advanced methods [#advanced-methods] ### ALL ROWS [#all-rows-] In Apex SOQL queries it's possible to retrieve "all records", including records from Recycle Bin and archived Tasks or Events, by appending `ALL ROWS`. This is comparable to the `queryAll()` option via API, and enables the `WHERE IsDeleted = true` condition, which normally returns an empty data set. ```apex qf.setAllRows( true ); ``` *** ### Aggregate queries (GROUP BY, HAVING, SOQL functions) [#aggregate-queries-group-by-having-soql-functions-] When in need for a `SUM`, `COUNT`, `MIN` or `MAX`, you can query all records and loop in Apex, but when not needing the individual records it is more efficient to let SOQL perform the logic with [aggregate queries](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_agg_functions.htm) and keep code cleaner. These queries are set up the same way as standard queries (select, condition, group by), but have a couple considerations: * Fields should be consciously added to avoid a SOQL error , thus excluding default fields (`newQueryFactory( false )`) * SOQL functions and aliases can be added via the standard (`selectFields( new Set{ 'COUNT( Id ) numOpenReservations } );`) * `setGroupByField()` registers the `GROUP BY` field. This automatically clears the `ORDER BY` by default (unless `true` is passed for the `preserveOrderings`-variable) * The results are `dfflib_AggregateResult` rows, thus not `SObject` records, which implies values are accessed by alias String rather than field token (`dfflib_AggregateResult.get( 'numOpenReservations' )`). Below are two examples to share some use-cases, method signatures and how to properly implement, call and mock `dfflib_AggregateResult`. Use the tabs to navigate between the selector, calling and unit test method and the database return format. **Example 1: `COUNT` of records for one `GROUP BY` field** Selector Response Calling method Unit test ```apex title="SEL_RoomReservations.selectOpenCountPerRoomId" repo="classes/SEL_RoomReservations.cls" public List selectOpenCountPerRoomId( Set roomIds ){ dfflib_QueryFactory qf = newQueryFactory( false ); qf.selectField( RoomReservation__c.Room__c ); qf.selectField( 'COUNT( Id ) numOpenReservations' ); List conditions = new List{ 'Room__c IN :roomIds', 'Status__c IN :openStatuses' }; qf.setCondition( String.join( conditions, ' AND ' ) ); qf.setGroupByField( RoomReservation__c.Room__c ); return this.executeAggregateQuery( qf, new Map{ 'roomIds' => roomIds, 'openStatuses' => DOM_RoomReservations.STATUSES_OPEN } ); } // SELECT Room__c, COUNT( Id ) numOpenReservations // FROM RoomReservation__c // WHERE Room__c IN :roomIds AND Status__c IN :openStatuses // GROUP BY Room__c ``` ```js [ { "result" : { "attributes" : { "type" : "AggregateResult" }, "Room__c" : "a01Dz00000SSfALIA1", "numopenreservations" : 2 } } ] ``` ```apex title="DOM_Rooms.ValidateDeactivation.finalize" repo="classes/DOM_Rooms.cls" // Validate whether any open reservations for the deactivated rooms, bypass sharing for data correctness List numOpenReservationsPerRoom = SEL_RoomReservations .newInstance( dfflib_Database.Context.NONE ).selectOpenCountPerRoomId( deactivatedRoomIds ); Map roomsById = new Map( ( List ) state.currentList ); for( Integer i = 0, j = numOpenReservationsPerRoom.size(); i < j; i++ ){ dfflib_AggregateResult result = numOpenReservationsPerRoom[ i ]; Id roomId = ( Id ) result.get( 'Room__c' ); if( Integer.valueOf( result.get( 'numOpenReservations' ) ) > 0 ){ Room__c roomToSetError = roomsById.get( roomId ); roomToSetError.addError( 'Cannot deactivate a room with open reservations.' ); } } ``` ```apex title="DOM_RoomsTest.validateDeactivation_withOpenReservations" repo="classes/DOM_RoomsTest.cls" // Shortened version focusing to mock dfflib_AggregateResult. Click GitHub icon on right for full code snippet. // Create mocks fflib_ApexMocks mocks = new fflib_ApexMocks(); // [!code highlight] dfflib_AggregateResult aggResult = ( dfflib_AggregateResult ) mocks.mock( dfflib_AggregateResult.class ); // [!code highlight] SEL_RoomReservations m_selReservations = ( SEL_RoomReservations ) dfflib.selector.defineMock( mocks, SEL_RoomReservations.class, RoomReservation__c.SObjectType ); // Given - set data Id roomId = fflib_IDGenerator.generate( Room__c.SObjectType ); Integer numOpenReservations = 3; // Set mocks mocks.startStubbing(); // [!code highlight:4] mocks.when( m_selReservations.selectOpenCountPerRoomId( expectedRoomIds ) ) .thenReturn( new List{ aggResult } ); mocks.when( aggResult.get( 'Room__c' ) ).thenReturn( roomId ); mocks.when( aggResult.get( 'numOpenReservations' ) ).thenReturn( numOpenReservations ); mocks.stopStubbing(); ``` **Example 2: `SUM` with a multi-field `GROUP BY`, `HAVING` filter and ordering by aggregate alias** **Context**: Imagine a WorkOrder which contains work for multiple parties, and should therefore be invoiced separately. Fixed callout costs should be invoiced to the Account which, by ratio, consumed the most work. Thus, the Account with the highest sum of duration over all WorkOrderLineItems should pay the costs. If the time spent is less than 10 minutes no fixed costs will be charged. **Requirement**: This requires a SOQL query which groups by two fields (`WorkOrderId` and `Paying_Account__c`), filters to only receive Accounts *having* at least 10 minutes of work performed for that WorkOrder and sorts them negatively to have the Account with the highest sum on top, to avoid the need for looping. Selector Response Calling method Unit test ```apex public List selectSumDurationPerPayingAccount( Set workOrderIds ){ dfflib_QueryFactory qf = newQueryFactory( false ) .selectFields( new List{ WorkOrderLineItem.WorkOrderId, WorkOrderLineItem.Paying_Account__c } ) .selectFields( new Set{ 'SUM( DurationInMinutes ) duration' } ) .setCondition( 'WorkOrderId IN :workOrderIds' ) .setGroupByField( 'WorkOrderId, Paying_Account__c' ) .setHaving( 'SUM( DurationInMinutes ) > 10' ) .setOrdering( 'SUM( DurationInMinutes )', dfflib_QueryFactory.SortOrder.DESCENDING ); return this.executeAggregateQuery( qf, new Map{ 'workOrderIds' => workOrderIds } ); } // SELECT WorkOrderId, Paying_Account__c, SUM( DurationInMinutes ) duration // FROM WorkOrderLineItem // GROUP BY WorkOrderId, Paying_Account__c // HAVING SUM( DurationInMinutes ) > 10 // ORDER BY duration DESC ``` ```js [ { "result" : { "attributes" : { "type" : "AggregateResult" }, "WorkOrderId" : "0WOP4000009eKFlOAM", "Paying_Account__c": "001Dz00000SSfALIA1", "duration" : 30 } }, { "result" : { "attributes" : { "type" : "AggregateResult" }, "WorkOrderId" : "0WOP4000009eKFlOAM", "Paying_Account__c": "001Dz00000SSfALIA1", "duration" : 20 } }, { "result" : { "attributes" : { "type" : "AggregateResult" }, "WorkOrderId" : "0WOP4000009bv3lOAA", "Paying_Account__c": "001Dz00002wI6C5IAK", "duration" : 42 } } ] ``` ```apex // Flow Invocable method to get Paying Account with highest duration-sum per WorkOrder List results = SEL_WorkOrderLineItems .newInstance( dfflib_Database.Context.FULL).selectSumDurationPerPayingAccount( new Set( workOrderIds ) ); Map maxSumDurationPerWO = new Map(); Map maxPayingAccountPerWO = new Map(); for( Integer i = 0, j = results.size(); i < j; i++ ){ dfflib_AggregateResult res = results[ i ]; Id woId = ( Id ) res.get( 'WorkorderId' ); Decimal currWOPASum = ( Decimal ) res.get( 'duration' ); Decimal currMax = maxSumDurationPerWO.get( woId ) ?? 0; // Compare current max to next-Paying-Account aggregate sum // When current smaller, set the Paying Account as new 'highest' // When equal, no Paying Account should be returned if( currMax < currWOPASum ){ maxPayingAccountPerWO.put( woId, ( Id ) res.get( 'Paying_Account__c' ) ); maxSumDurationPerWO.put( woId, currWOPASum ); } else if( currMax == currWOPASum ){ maxPayingAccountPerWO.put( woId, null ); } } ``` ```apex @IsTest private static void getPayingAccountWithHighestDurationSumPerWorkOrderId(){ // [!code word:mocks2] // [!code word:mocks3] // [!code highlight:4] // create three mock-stubproviders to allow distinct method returns for identical method calls of aggregate results fflib_ApexMocks mocks = new fflib_ApexMocks(); fflib_ApexMocks mocks2 = new fflib_ApexMocks(); fflib_ApexMocks mocks3 = new fflib_ApexMocks(); SEL_WorkOrderLineItems m_selWOLIs = ( SEL_WorkOrderLineItems ) dfflib.selector.defineMock( mocks, SEL_WorkOrderLineItems.class, WorkOrderLineItem.SObjectType ); // Given - set data (2 workorders, 2 paying accounts, 3 aggregate results) // [!code highlight:3] dfflib_AggregateResult aggResultWO1 = ( dfflib_AggregateResult ) mocks.mock( dfflib_AggregateResult.class ); dfflib_AggregateResult aggResultWO2a = ( dfflib_AggregateResult ) mocks2.mock( dfflib_AggregateResult.class ); dfflib_AggregateResult aggResultWO2b = ( dfflib_AggregateResult ) mocks3.mock( dfflib_AggregateResult.class ); Id wo1 = fflib_IDGenerator.generate( WorkOrder.SObjectType ); Id wo2 = fflib_IDGenerator.generate( WorkOrder.SObjectType ); Id pa1 = fflib_IDGenerator.generate( Account.SObjectType ); Id pa2 = fflib_IDGenerator.generate( Account.SObjectType ); List inputIds = new List{ wo1, wo2 }; // set mocks mocks.startStubbing(); // [!code highlight:2] mocks.when( m_selWOLIs.selectSumDurationPerPayingAccount( ( Set ) fflib_Match.anyObject() ) ) .thenReturn( new List{ aggResultWO1, aggResultWO2a, aggResultWO2b } ); mocks.when( aggResultWO1.get( 'WorkorderId' ) ).thenReturn( wo1 ); mocks.when( aggResultWO1.get( 'Paying_Account__c' ) ).thenReturn( pa1 ); mocks.when( aggResultWO1.get( 'duration' ) ).thenReturn( 5.5 ); mocks.stopStubbing(); mocks2.startStubbing(); mocks2.when( aggResultWO2a.get( 'WorkorderId' ) ).thenReturn( wo2 ); mocks2.when( aggResultWO2a.get( 'Paying_Account__c' ) ).thenReturn( pa1 ); mocks2.when( aggResultWO2a.get( 'duration' ) ).thenReturn( 10 ); mocks2.stopStubbing(); mocks3.startStubbing(); mocks3.when( aggResultWO2b.get( 'WorkorderId' ) ).thenReturn( wo2 ); mocks3.when( aggResultWO2b.get( 'Paying_Account__c' ) ).thenReturn( pa2 ); mocks3.when( aggResultWO2b.get( 'duration' ) ).thenReturn( 10 ); mocks3.stopStubbing(); // When - perform test List payingAccountIds = Flow_GetAccountWithHighestDuration.getPayingAccountWithHighestDurationSumPerWorkOrderId( inputIds ); // Then - validate wo1 had highest and wo2 as null as equal value System.Assert.areEqual( inputIds.size(), payingAccountIds.size(), 'Expected same number response as input' ); System.Assert.areEqual( pa1, payingAccountIds[ 0 ], 'Expected first WO Id to return PA1 as only one, being the highest' ); System.Assert.areEqual( null, payingAccountIds[ 1 ], 'Expected second WO Id to return null, as two Paying Accounts have same sum' ); } ``` `fflib_ApexMocks` ties each stubbed return to its own mock instance (`this`). Thus, a sequential stub on the same mocked instance (Domain, Selector, AggregateResult) will overwrite earlier stubs on that instance. Hence, when the same method (`.get( 'duration' )`) must return a different value for each `dfflib_AggregateResult` instance, each instance needs its own `fflib_ApexMocks` instance. In the 'unit test' above, three instances and stub-blocks make it possible to imitate three separate `dfflib_AggregateResult` database row responses. It is essential to ensure the `fflib_ApexMocks` instance passed into the `defineMock()`, matches the `fflib_ApexMocks` instance used to stub the `dfflib_AggregateResult` instance. Above example shows the ability to query SObject related aggregates, specifying the fields to query, group, filter and order upon. It's important that all fields referenced are also included in the grouping to avoid `malformed query` errors. The response `List` contains the exact fields and aliases requested. Those can be simply 'looped' and should be cast to the expected datatype as the aggregate result is context independent. Note, the usage of `setOrdering()` which clears and sets. Though `addOrdering` would have worked as well, due to the default clearing/`emptyOrdering()` when calling `setGroupByField()`. When no alias is set (like `duration`), Salesforce will return `expr0`, `expr1`, .... Note, Salesforce doesn't allow aliases to be used within the query, like `HAVING duration` or `ORDER BY duration` Due to the builder structure of the QueryFactory, it's possible to 'chain' the methods. In which the sequence of method-calls has no effect for the resulting query. *** ### Cursor and Pagination Cursor [#cursor-and-pagination-cursor-] In [Spring '26](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_cursors.htm) `Database.Cursor` became generally available, which allows cursor-based navigation through large result sets without the 2,000-record ceiling that `OFFSET` imposes. This is particularly useful for UIs that need to stream through thousands of records efficiently. The structure of the selector method remains the same, only the final execution method should be `this.getCursor()` or `this.getPaginationCursor()`, providing the same parameters as `this.executeQuery()` (`dfflib_QueryFactory` and optional bind-variable map). ```apex // Instead of executeQuery(), call getCursor() or getPaginationCursor() for cursor-based navigation return this.getCursor( qf, bindVars ); // Database.Cursor return this.getPaginationCursor( qf, bindVars ); // Database.PaginationCursor ``` The framework automatically validates whether no `GROUP BY` or `FOR UPDATE` is set, or will throw an `InvalidCursorQueryException` as these are incompatible with Cursors. *** ### FOR VIEW, REFERENCE and UPDATE [#for-view-reference-and-update-] Salesforce has three SOQL `FOR` clauses that control record-tracking and locking behaviour: | SOQL Command | Description/use-case | | --------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | [FOR VIEW](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_for_view_for_reference.htm) | Retrieve records for read-only display (UI views); use when you only need to show data without modifying it. | | [FOR REFERENCE](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_for_view_for_reference.htm) | Retrieve records to use as references (e.g., populate lookups or obtain Ids); use when you need stable identifiers or reference data. | | [FOR UPDATE](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_for_update.htm) | Lock returned rows for the duration of the transaction to prevent concurrent modifications; use before performing DML to avoid race conditions. | To support developers to leverage `dfflib_QueryFactory` when in need for these methods, one can append via below methods: ```apex qf.setForView( true ); // marks retrieved records as recently viewed by the running user qf.setForReference( true ); // marks retrieved records as recently referenced qf.setForUpdate( true ); // row-locks retrieved records for the duration of the transaction ``` * `FOR UPDATE` is incompatible with `ORDER BY`. Call `emptyOrdering()` to prevent a runtime exception by Salesforce * When both `FOR VIEW` and `FOR REFERENCE` are set, an `InvalidImplementationException` is thrown as those are mutually exclusive *** ### Location based queries [#location-based-queries] To enable [location-based SOQL queries](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_geolocate.htm), SOQL has a `DISTANCE( field, GEOLOCATION( latitude, longitude ), unit )` method which calculates the distance, in kilometres ('km') or miles ('mi'), from each record's location to the specified geolocation. This can be applied in the `SELECT`, `WHERE` and `ORDER BY` sections, and can be set via the standard methods, passing a String, as shown below. The `getDistanceString( SObjectField, DistanceUnit )` was introduced to take away overhead from developers about finding the exact signature, parameter sequence, but also the restriction of `unit` not being allowed as bind-variable, and the cumbersome mapping towards 'km' and 'mi'. This method performs the `getFieldPath` and simply returns the `DISTANCE` expression via an easy to (re-)use method. Consider assigning the `DISTANCE` expression to a variable when reusing across SOQL sections. ```apex title="SEL_Rooms.selectNearestRooms" repo="classes/SEL_Rooms.cls" public List selectNearestRooms( Decimal latitude, Decimal longitude, Decimal radiusKm ){ dfflib_QueryFactory qf = newQueryFactory( false ); String distanceString = qf.getDistanceString( Room__c.Location__c, dfflib_QueryFactory.DistanceUnit.KILOMETERS ); qf.selectField( distanceString ); qf.setCondition( distanceString + '< :radiusKm' ); qf.setOrdering( distanceString, dfflib_QueryFactory.SortOrder.ASCENDING, true ); return this.executeQuery( qf, new Map{ 'latitude' => latitude, 'longitude' => longitude, 'radiusKm' => radiusKm } ); } // SELECT DISTANCE( location__c, GEOLOCATION(:latitude, :longitude), 'km' ) // FROM Room__c // WHERE DISTANCE( Location__c, GEOLOCATION(:latitude, :longitude), 'km' ) < :radiusKm // ORDER BY DISTANCE( Location__c, GEOLOCATION(:latitude, :longitude), 'km' ) ASC NULLS LAST ``` * The `DistanceUnit` enum includes `KILOMETERS` and `MILES` . * Distance-conditions only accept `<` or `>` operators, `=`, `<=` and `>=` aren't allowed. *** ### Pagination (LIMIT, OFFSET) [#pagination-limit-offset-] * `LIMIT` is used to restrict the number of records retrieved and required for queries with `FIELDS(ALL)`, `FIELDS(CUSTOM)` or applying `OFFSET`. This is mostly relevant to manage performance or avoid retrieving unnecessary data. * `OFFSET` allows you to skip a specified number of records, till a limit of 2,000 records, making it useful for (smaller) pagination or batch-processing. For larger data sets, use `getQueryLocator()` (Batch Apex) or `getCursor()` instead. ```apex qf.setLimit( 50 ); qf.setOffset( 100 ); ``` Ensure to have a strict `ORDER BY` so the data scope remains the same. *** ### Polymorphic fields (TYPEOF) [#polymorphic-fields-typeof-] To query parent-fields from a [polymorphic field](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_and_polymorph_keys.htm) SOQL provides: ``` TYPEOF [FIELD] WHEN [OBJECT] THEN [FIELDS] WHEN [OBJECT2] THEN [FIELDS2] ELSE [FIELDS3] END ``` This way lookup fields like `Owner` (can be a `Group` or `User`) or `WhoId` (can be a `Contact` or `Lead`) can be specifically queried. Developers can leverage `selectFieldsTypeOf()` , passing the field name and a map of `SObjectType` to `Set` to define what to retrieve per `SObjectType`. Selector Calling method ```apex public List selectWhoInfo( Set taskIds ){ dfflib_QueryFactory qf = newQueryFactory( false ); // [!code highlight:4] qf.selectFieldsTypeOf( 'Who', new Map>{ Contact.SObjectType => new Set{ Contact.FirstName, Contact.LastName, Contact.Email }, Lead.SObjectType => new Set{ Lead.FirstName, Lead.LastName, Lead.Company, Lead.Email } } ); qf.setCondition( 'Id IN :taskIds' ); qf.setOrdering( Task.ActivityDate, dfflib_QueryFactory.SortOrder.ASCENDING ); return this.executeQuery( qf, new Map{ 'taskIds' => taskIds } ); } // SELECT TYPEOF Who // WHEN Contact THEN FirstName, LastName, Email // WHEN Lead THEN FirstName, LastName, Company, Email // END // FROM Task // WHERE Id IN :taskIds // ORDER BY ActivityDate ASC NULLS FIRST ``` ```apex List tasksList = SEL_Tasks.newInstance( dfflib_Database.Context.FULL ).selectWhoInfo( taskIdsSet ); for( Integer i = 0, j = tasksList.size(); i < j; i++ ){ Task t = tasksList[ i ]; if( t.Who instanceof Contact ){ Contact c = ( Contact ) t.Who; // Perform magic } else if( t.Who instanceof Lead ){ Lead l = ( Lead ) t.Who; // Perform magic } } ``` Note, `TYPEOF` is only valid for polymorphic lookup fields and can't be combined with `GROUP BY`. *** ## Testing a Selector [#testing-a-selector] The responsibilities of selectors are to construct a SOQL query and call the database with the correct variables. This implies a unit test method should assert exactly those two responsibilities. Implying there is no need to validate whether the database indeed returned the correct data, as that concern is separated to the Database Proxy and standard Salesforce. ### Assertion methods [#assertion-methods-] Effectively this means mocking the `dfflib_Database_IQuery` and performing a `mocks.verify()` on the `query()` method to capture the SOQL string and optional bind-variables. For ease of use, centralisation and deduplication of code, D'fflib provides below set of methods to 1) mock the proxy, 2) verify query execution and 3) validate constructed query and bind-variables . **1. Mock the database proxy** | Method | What it does | | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | `mockExecuteQuery()` | Mocks the database proxy for standard queries; returns the `fflib_ApexMocks` instance | | `mockExecuteAggregateQuery()` | Same as above, but also pre-stubs an empty `List` return so the internal cast to `List` succeeds | **2. Verify the query execution method was properly called** After the selector execution ('WHEN'), the `verify*()`-methods assert whether the query was executed. Optionally comparing the number of variables and bind-variables provided. Returning inner-class `SelectorVerificationResults` for method-specific validation: | Method | Verifies | | ---------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | `verifyQuery( mocks )` | `executeQuery()` was called **without** a bind-variable map | | `verifyQueryAndBindVariableKeys( mocks )` | `executeQuery()` was called **with** a bind-variable map, and every `:bindVar` in the query string has a matching key in the map | | `verifyQueryLocator( mocks )` | Same as `verifyQuery()` but for `getQueryLocator()` calls | | `verifyQueryLocatorAndBindVariableKeys( mocks )` | Same as `verifyQueryAndBindVariableKeys()` but for `getQueryLocator()` calls | | `verifyCursor( mocks )` | Same as `verifyQuery()` but for `getCursor()` calls | | `verifyCursorAndBindVariableKeys( mocks )` | Same as `verifyQueryAndBindVariableKeys()` but for `getCursor()` calls | | `verifyPaginationCursor( mocks )` | Same as `verifyQuery()` but for `getPaginationCursor()` calls | | `verifyPaginationCursorAndBindVariableKeys( mocks )` | Same as `verifyQueryAndBindVariableKeys()` but for `getPaginationCursor()` calls | **3. Validate specific SOQL parts via `SelectorVerificationResults` methods and variables** ```apex public class SelectorVerificationResults { dfflib_QueryFactory qf; // The QueryFactory instance used to construct the query String query; // The SOQL query string injected into the database proxy Map map_bindVariables; // The bindvariables map injected into the database proxy } ``` | Method | What it asserts | | ---------------------------------------------- | ------------------------------------------------------------------------ | | `.validateTable( SObjectType )` | `FROM` clause matches the expected SObject type | | `.validateFields( Set )` | All specified fields are present in the `SELECT` clause | | `.validateCondition( String )` | `WHERE` clause exactly matches the expected condition (case-insensitive) | | `.validateCondition( String, true )` | `WHERE` clause **contains** the expected condition (partial match) | | `.validateBindVariableValue( key, value )` | A specific bind variable in the map equals the expected value | ### Example [#example] Standard query Aggregate query ```apex title="SEL_RoomReservationsTest.selectByRoomId" repo="classes/SEL_RoomReservationsTest.cls" @IsTest private static void selectByRoomId(){ // create mocks to prevent database calls SEL_RoomReservations selector = SEL_RoomReservations.newInstance( dfflib_Database.Context.FULL ); fflib_ApexMocks mocks = selector.mockExecuteQuery(); // Given - setup Set to validate bind-passing Set roomIds = new Set(); // When - perform test selector.selectByRoomId( roomIds ); // Then - validate query, condition and fields selector.verifyQueryAndBindVariableKeys( mocks ) .validateCondition( 'Room__c IN :roomIds' ) .validateBindVariableValue( 'roomIds', roomIds ) .validateFields( new Set{ RoomReservation__c.Room__c, RoomReservation__c.Status__c } ); } ``` ```apex title="SEL_RoomReservationsTest.selectOpenCountPerRoomId" repo="classes/SEL_RoomReservationsTest.cls" @IsTest private static void selectOpenCountPerRoomId(){ // create mocks to prevent database calls - use mockExecuteAggregateQuery for aggregate queries SEL_RoomReservations selector = SEL_RoomReservations.newInstance( dfflib_Database.Context.FULL ); fflib_ApexMocks mocks = selector.mockExecuteAggregateQuery(); // Given - setup Set to validate bind-passing Set roomIds = new Set(); // When - perform test selector.selectOpenCountPerRoomId( roomIds ); // Then - validate query, condition and fields (use Set for aggregate fields) dfflib_QueryFactory qf = selector.verifyQueryAndBindVariableKeys( mocks ) .validateFields( new Set{ 'Room__c', 'COUNT( Id ) numOpenReservations' } ) .validateCondition( 'Room__c IN :roomIds AND Status__c IN :openStatuses' ) .validateBindVariableValue( 'roomIds', roomIds ) .validateBindVariableValue( 'openStatuses', DOM_RoomReservations.STATUSES_OPEN ) .qf; System.Assert.areEqual( 'Room__c', qf.getGroupByField(), 'Expected Group by on Room__c' ); } ``` Before the introduction of the Database Proxy, thus when having `Database.query()` as last statement in the selector method, it was not possible to properly assert the constructed query, nor the bind variables passed to it. Because of this asserts were often a 'formality' and not really adding any value, other than covering lines. Often developers chose to: * Create data and validate a proper return. Causing longer unit-test runtimes. * Use `Limits.getQueries()` to assert the number of queries performed. Only validating the execution, but not the query. * Track the `@TestVisible lastQueryFactory` in `dfflib_QueryFactory` which is set upon `toSOQL()` to allow assertions. This implies developers (and reviewers) should become conscious of properly asserting the selector method's responsibilities. *** ## Migration steps [#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](/dfflib/docs/how/get-started)), thus e.g. already having the `override` added in all existing Selectors. **Class changes** 1. Ensure `Dfflib_Selector_Config__mdt` record exists 2. Change `extends fflib_SObjectSelector` to `extends dfflib_SObjectSelector` 3. Change `[Application].selector.newInstance()` to `dfflib.selector.newInstance()` 4. Create an overload or update the existing `.selector.newInstance()` to receive a `dfflib_Database.Context`. Recommendation is to construct this dynamically via an input-parameter, but this requires all calling-classes to pass the applicable `dfflib_Database.Context`. Another option is to use a default context, set in the `newInstance` method of the Selector. D'fflib selector ```apex public static SEL_Assets newInstance( dfflib_Database.Context ctx ){ return ( SEL_Assets ) dfflib.selector.newInstance( Asset.SObjectType, ctx ); } public static SEL_Assets newInstance(){ return ( SEL_Assets ) dfflib.selector.newInstance( Asset.SObjectType, dfflib_Database.Context.FULL ); } ``` When dynamic, find and replace `SEL_[SObjects].newInstance()` calls to include the `dfflib_Database.Context`. 5. Validate `sharing` annotation of Selector class and relevancy/reasoning\ Best practice is `with sharing` (still used e.g. when calling `SObjectDescribe` methods) **Method changes** 1. Simplify `newQueryFactory`-call, by removing `enforce`-Booleans 2. Change `fflib_QueryFactory` to `dfflib_QueryFactory` 3. Replace `Database.query` by `this.executeQuery()`\ or the equivalent for `Cursor`, `QueryLocator`, or aggregate queries 4. Pass bind variables via a Map\ Decommission need for local 'copies' of static variables (like `String recordType = DOM_Accounts.RECTYPE_BUSINESS`) as this can now directly be set to the Map 5. Remove `without sharing` inner-classes and `withSharing` Boolean parameters **Test class changes** 1. Omit any test data creation or `Limits.getQueryRows()` 2. Mock the query to prevent execution via `mockExecuteQuery()` (or `mockExecuteAggregateQuery()`) 3. Add strict assert to validate proper query construction leveraging provided [Assertion methods](#assertion-methods-) When using `enforceFLS` fields are validated and deduplicated by `SObjectDescribe`. With the migration to `FLSEnforcement` and `dfflib_Database.Context` the field-validation became server-side, while the deduplication is still desired to prevent SOQL errors. Therefore the QueryFactory automatically converts fields to lowercase to allow deduplication. For manual asserts it's therefore important to validate against lowercase fields. `validateFields()` automatically converts to lowercase. Legacy constructs with `enforceFLS` keep their input casing. --- # Services URL: /dfflib/docs/how/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 [#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 [#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](/dfflib/docs/how/overview#domain-vs-service-ambiguity)). Multiple Services per process are valid, like `SRV_OpportunityRenewal` and `SRV_OpportunityMACD` living side by side with a lean `DOM_Opportunities`. ### Interactions [#interactions] | Interaction | Layers | | ----------- | ------------------------------------------------------------------ | | Called by | API, Entrypoints, Batch `execute()`, other Services (with caution) | | Calling | Selectors, 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 [#rules] * Methods should have a clear single responsibility. * Methods should be robust and satisfy the [open-close principle](https://en.wikipedia.org/wiki/Open%E2%80%93closed_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` or `List` 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 [#initiation] ### How to call [#how-to-call] Comparable to other layers, Services are instantiated via `newInstance()`, enabling mocking. ```apex title="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. ```apex SRV_RoomReservations serviceDirect = ( SRV_RoomReservations ) dfflib.service.newInstance( SRV_RoomReservations.class ); ``` ### Class boilerplate [#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. ```apex public with sharing class SRV_RoomReservations{ public static SRV_RoomReservations newInstance(){ return ( SRV_RoomReservations ) dfflib.service.newInstance( SRV_RoomReservations.class ); } // Service methods and implementation.... } ``` ```apex @RestResource( UrlMapping = '/Room/Cancellation/*' ) global with sharing class SRVi_RoomCancellation{ @HttpPost global static void handleRequest(){ // Integration magic } } ``` 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 [#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: | Field | Purpose | Example | | ------------------------ | ----------------------------------------------------------------------------------------- | --------------------------------------------------------- | | `MasterLabel` | Label of the mdt record. Shown in Setup | `SRV_RoomReservations` | | `DeveloperName` | Unique API name of the record. Doesn't allow duplicate (`___`) thus namespace with single | `SRV_RoomReservations` | | `Interface_Type__c` | Interface the Service is resolved by | `SRV_RoomReservations` or `SRV_RoomReservations.IService` | | `Implementation_Type__c` | Class implementing the Service | `SRV_RoomReservations` | *** ## Code examples [#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`](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/SRVo_PostalCodeValidation.cls). | Class | Context | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- | | [SRV_Request](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/SRV_Request.cls) | HTTP request builder | | [SRV_Response](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/SRV_Response.cls) | Standardised LWC & HTTP Response builder | | [SRVo_PostalCodeValidation](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/SRVo_PostalCodeValidation.cls) | Outgoing integration to validate postal codes | | [SRVo_PostalCodeValidationTest](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/SRVo_PostalCodeValidationTest.cls) | Unit test for outgoing integration | *** ## Migration steps [#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](/dfflib/docs/how/get-started)). **Required changes** 1. Ensure `Dfflib_Service_Config__mdt` record exists 2. Change `[Application].service.newInstance()` to `dfflib.service.newInstance()` D'fflib Service fflib-apex-common Service ```apex // [!code word:dfflib] public with sharing class SRVo_PostalCodeValidation{ public static SRVo_PostalCodeValidation newInstance(){ return ( SRVo_PostalCodeValidation ) dfflib.service.newInstance( SRVo_PostalCodeValidation.class ); } } ``` ```apex public with sharing class SRVo_PostalCodeValidation{ public static SRVo_PostalCodeValidation newInstance(){ return ( SRVo_PostalCodeValidation ) Application.service.newInstance( SRVo_PostalCodeValidation.class ); } } ``` --- # Testing & Mocking URL: /dfflib/docs/how/testing-mocking/ Elaborating on the benefits of mocking, and how to properly set up test data to mock methods with. Including thorough and extensive example code snippets. This article is under construction and will be released shortly. The outline already shows the intended structure. * Until this article is finalised, our blog post "[Extensive test/mocking example guide in fflib](https://deloitte-engineering.github.io/2022/extensive-test-mocking-example-guide-in-fflib/)" already takes you along mocking, stubbing, verification and test data builders end to end. * D'fflib-specific shortcuts (e.g. selector assertion methods) are covered in the [Selectors](/dfflib/docs/how/selectors#testing-a-selector) article. ## Characteristics [#characteristics] {/*A unit test validates the logic of exactly one method, in isolation of the layers it depends on. It answers "does this class do what it should?" without depending on whether its dependencies do too.*/} ### Responsibilities [#responsibilities] {/* TODO: unit tests vs automated end-to-end / regression tests (testing pyramid). Unit tests: fast, many, one method each. E2E / regression: fewer, cross-layer, belong in the (automated) regression suite. Trigger unit tests can optionally act as regression tests, see Guidelines. */} {/* 1. Create fast feedback loop to catch regressions early 1. Ensure backward compatibility on original functionality after changes 1. Hammer test for Salesforce to validate new Salesforce releases 1. Documentation for new joiners on how method and business logic was originally intended 1. Unit test coverage It is NOT: end-to-end or regression testing. Testing pyramid */} ### Considerations [#considerations] 1. Test segregation: test single-responsibility vs. end-to-end tests in Apex Unit Tests; mocking everything, most or none (all data insertion) 2. Test deduplication: avoid testing the same logic multiple times by reusing test data builders and mocking dependencies {/*Why mock? Mocking a dependency means replacing it with a 'hollow' version whose responses are programmed by the test. This enables: - **Faster unit tests**: no DML, no SOQL, fully parallelisable - **DRY test data**: records are defined once in a builder, not repeated per test method - **Single responsibility**: each test only validates the class under test, not its dependencies - **Exception coverage**: forcing a dependency to throw, without `Test.isRunningTest()` in production code */} ### Rules [#rules] {/* TODO: capture values in variables for both stub and verify. - Only test single-responsibility of test method - Avoid covering same code twice - Minimise database interactions, e.g. by mocking - When requiring insertions, leverage TestFactory to centralise and avoid duplication */} *** ## Initiation [#initiation] ### How to call [#how-to-call] Test classes are never called from code. They're run through the Salesforce CLI, either as part of a release (by the deployment test level), separately, or by a manual run from the Developer Console or Setup. ```bash sf apex run test --class-names CTRL_RoomReservationsTest ``` ### Class guideline [#class-guideline] Below skeleton is a suggestion for how to structure test classes for ease of readability and maintenance. Reasoning is elaborated in the [Guidelines section](/dfflib/docs/how/guidelines#test-classes). ```apex lineNumbers @IsTest( isParallel = true ) private with sharing class CTRL_RoomReservationsTest{ @IsTest private static void methodName_scenario(){ // Create mocks // Given - create data // Set mocks // When - perform test // Then - validate ... } } ``` {/* Best practices of no Test.startTest(); method naming; isParallel default; private with sharing default; */} *** ## Standard methods [#standard-methods] Each unit test follows the same three steps: construct the test data, mock the dependencies, and verify whether the single-responsibility was satisfied, by asserting return values and layer-interactions. This article follows one scenario from start to end: the Room Booking controller [`CTRL_RoomReservations`](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/CTRL_RoomReservations.cls) and its test class [`CTRL_RoomReservationsTest`](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/CTRL_RoomReservationsTest.cls). {/* TODO: walk through the code under test before showing the tests. */} ### 1. Test data [#1-test-data] {/* TODO: create the records needed for the scenario. */} This section will show how to construct the test data for the scenario, using the [Test Data Builder Framework](#test-data-builder-framework). {/* Test data builders are registered in `TestFactory`, not in custom metadata. See [Anatomy of a builder](#anatomy-of-a-builder). */} *** ### 2. Mock dependencies [#2-mock-dependencies] This section will show how to replace each dependency of the class under test by a mock, and how to program its responses. The terms stubbing and mocking are often used interchangeably, but this isn't factually correct. Stubbing means faking a response, and mocking is verifying the interaction. #### Stub classes [#stub-classes] * Expected behaviour for methods on a stubbed class #### Override behaviour [#override-behaviour] * Void vs. non-void methods * Link to Matchers section (to centralise for stubbing and mocking) {/* TODO: mocks.startStubbing(); mocks.when( ... ).thenReturn( ... ); mocks.stopStubbing(); */} {/* TODO: doAnswer / doThrowWhen on void methods such as Unit of Work registrations. */} #### Inject mocks [#inject-mocks] * How to pass into (D')fflib and the internal mechanics #### defineMock() [#definemock] * Simplified way to create and register a mock in one step {/* TODO: one-line mock setup per layer; validate signatures against framework source before adding snippets. */} ### 3. Verification [#3-verification] {/* TODO: mocks.verify( mock, times ) for interactions, including Unit of Work registrations and commitWork. */} * Return variable * Layer interactions * Link to Matchers section (to centralise for stubbing and mocking) * ArgumentCaptor *** ### Matchers [#matchers] * Guidance regarding either all matchers on none * Different Matcher methods (eq, sObjectWith) {/* TODO: fflib_Match usage and when to prefer exact values. */} *** ## Test Data Builder Framework [#test-data-builder-framework] {/* TODO: introduction to TestFactory and builders. */} This section will cover how to define test data once and reuse it across all test classes. ### Anatomy of a builder [#anatomy-of-a-builder] {/* TODO: Builder class, naming sequence (as / for / add / is / with), registration in TestFactory. */} This section will cover how to create a builder and register it in `TestFactory`. ### Output modes [#output-modes] | Mode | Method | DB hit? | Ids populated? | Formula fields? | When to use | | --------------- | ---------------- | ------- | -------------- | --------------- | ---------------------------------------------- | | Pure mock | `.mock()` | ✗ | ✗ | ✓ | Unit tests where no Id is needed | | Mock with IDs | `.mockWithIds()` | ✗ | ✓ (fake) | ✓ | Unit tests that read `.Id` or traverse lookups | | Database insert | `.save()` | ✓ | ✓ (real) | ✗ | Integration tests requiring real records | Example JSON output ### Advanced features [#advanced-features] * `dfflib_UT_Utils` with SaveResults, `createSObjectList`, Profile cache, * SObjectType defined defaults * Replacers for autonumbers, or random values {/* - autonumber, static resource, dfflib_UT_Utils */} *** ## Layer specific tests [#layer-specific-tests] Each layer article covers how to test that layer in isolation: * [Domain](/dfflib/docs/how/domains#testing-a-domain) * [Entrypoint](/dfflib/docs/how/entrypoints#testing-an-entrypoint) * [Selector](/dfflib/docs/how/selectors#testing-a-selector) * Service * [Trigger Handler](/dfflib/docs/how/trigger-handlers#testing-a-trigger) * [Unit of Work](/dfflib/docs/how/unit-of-work#testing-a-unit-of-work) Trigger coverage Salesforce requires [every trigger to have some test coverage](https://help.salesforce.com/s/articleView?id=platform.code_run_tests.htm\&type=5) before it can be deployed. In a codebase which fully adopted (D')fflib, Domain and handler tests mock all DML, so no SObject is inserted or updated and the triggers stay at 0% coverage, causing deployments to fail. While we're defensive on adding code "just for the sake of code coverage", this is the one place where real DML is intended. An option for this is to: * Create one `TriggersTest` class, with one test method per SObject that has a trigger, like [TriggersTest](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/TriggersTest.cls). * Each method performs a single real insert of a minimal record, which executes the trigger and its `triggerHandler()` call. * Don't assert business logic here: the handlers are already tested in isolation, see [Testing a Trigger](/dfflib/docs/how/trigger-handlers#testing-a-trigger). Asserting it again tests the same logic twice and makes the test fragile to unrelated handler changes. * Add a method to this class whenever a new trigger is added. Alternatively, an end-to-end test that already inserts the SObject covers its trigger as well. *** ## Migration steps [#migration-steps] No migration steps are required to realise a compilable D'fflib codebase. However, once D'fflib is installed ([Getting Started](/dfflib/docs/how/get-started)), we suggest leveraging these functionalities to reduce unit test runtimes and make test methods more readable and maintainable. 1. **Selector unit tests**\ After upgrading Selectors, avoid the query to be performed, saving precious time. Follow the "Test class changes" in the [Selectors migration steps](/dfflib/docs/how/selectors#migration-steps) to replace data creation by strict query assertions. 2. **Layer mocks to `defineMock()`** See before and after code [in the feature article](/dfflib/docs/what/accelerators-utilities#simplified--standardised-mocks). {/* TODO: add Before / After tabs once defineMock() signatures are validated against the framework source. */} 3. **Move inline test data to Builders** 1. When writing or touching a test class, identify inline SObject constructions (`new Account( ... )`, `insert acc`, repeated field assignments) 2. Create a builder for that SObject and move scenario-specific field combinations into `as*()` methods 3. Replace the inline constructions by `TestFactory` calls, keeping test-specific overrides on the builder call --- # Trigger Handlers URL: /dfflib/docs/how/trigger-handlers/ Step-by-step guide on how to set up and interact with Trigger Handlers, maximise the functions and benefits, while being aware of edge cases and D'fflib specific functionalities. We are finalising a redesign for the D'fflib trigger handler framework . Keeping the Handler structure, but moving registration to metadata, to allow a more flexible configuration, like (partial or temporary) disablement. This article has the single responsibility to elaborate on the trigger handlers registration and implementation.\ [→ Click here to visit the Domain documentation](/dfflib/docs/how/domains), to learn how those can be initiated and used. ## Characteristics [#characteristics] A Trigger Handler is a lean class, responsible for a specific process to happen upon a record-triggered event for a specific SObject. It can contain small business logic, or delegate to the appropriate Domain, Selector or Service method. ### Responsibilities [#responsibilities] Eligibility screening, to filter only records which match the business criteria for processing. Perform business process and/or validations on eligible records, or delegate to appropriate layer. Optionally, communicate the outcome, e.g. by registering to the Unit of Work or adding an error to the record. ### Interactions [#interactions] | Interaction | Layers | | ----------- | ---------------------------------------------------------------------------------------------- | | Called by | `dfflib_SObjectDomain` (the trigger framework) | | Calling | Domain (of same SObject), Selectors, Services, Unit of Work (only for deviating sharing modes) | The D'fflib Trigger Handler framework orchestrates the transactions and therefore injects a Unit of Work into a `BaseHandler`-implemented class. Handlers should, thus, only register, and not initiate nor `commitWork`, unless one Trigger Handler needs to bypass the `dfflib_Database.Context` ([→ see Handler-specific Context](#access-control)). ### Rules [#rules] * Only one Trigger should exist per SObject, delegating to the Trigger Handlers. * The Trigger only initiates the Trigger Framework, and optionally references project-specific bypassing/evaluation logic. Thus zero business logic. * Handlers should have a clear single responsibility. * Handlers' name should clearly describe the action it performs, e.g., `ValidateDeactivation`. Avoid generic names like `Handler1` or `AfterInsertHandler`. * Handlers should be robust and satisfy the [open-close principle](https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle). * Handlers should be bulkified to be scalable and reusable. * Handlers should consciously handle Exceptions, to properly log and not disrupt the overall trigger execution flow too much. * Handlers should leverage `TriggerState` and not directly use `Trigger.new` or `Trigger.old` to access record data, as those can't be mocked in unit tests. * Queries and DMLs should be restricted to `initialize()` and `finalize()`, since `process()` is called for each record. `fflib-apex-common` has no handler classes. A Domain overrides lifecycle hooks (`onBeforeInsert()`, `onValidate()`, etc.) and either holds the logic itself or delegates from there. The rules above apply unchanged to such hook implementations: one Trigger per SObject, zero business logic in the Trigger, bulkified, and no queries or DML inside record loops. Both styles can live in the same Domain, so existing hook-based Domains keep working when adopting D'fflib. *** ## Initiation [#initiation] ### How to call [#how-to-call] **Trigger**\ Triggers are automatically invoked by Salesforce upon DML events on the associated SObject. The trigger file delegates to the Trigger Handler Framework in the Domain, which runs the handlers registered for the fired event. ```apex title="RoomTrigger.trigger" repo="triggers/RoomTrigger.trigger" trigger RoomTrigger on Room__c ( before insert, before update, before delete, after insert, after update, after delete, after undelete ) { dfflib_SObjectDomain.triggerHandler( DOM_Rooms.class ); } ``` **Domain: handler registration**\ In [its constructor](/dfflib/docs/how/domains#class-boilerplate), a Domain class registers which handler responds to which event, with one `registerHandler` line per event-handler pair. One handler can be registered for multiple events. ```apex public DOM_RoomReservations( List sObjectList ){ super( sObjectList, dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL ) ); // Register handlers registerHandler( TriggerEvent.BEFORE_INSERT, CalculateTotalPrice.class ); registerHandler( TriggerEvent.BEFORE_UPDATE, CalculateTotalPrice.class ); } ``` The Trigger file is nearly identical: `fflib_SObjectDomain.triggerHandler( DOM_Rooms.class )`. The Domain constructor also stays the same, only without `registerHandler` lines. Instead of registering handler classes, the Domain overrides the hooks of `fflib_SObjectDomain` for the events it needs. The `on*` hooks are the bridge to the D'fflib handlers: their default implementation calls `execute()`, which runs the handlers registered for that event. An override that does not call `super` therefore bypasses the registered handlers of that event.
If you'd like to better understand what the D'fflib Trigger Handler Framework entails, check this article for an overview of its specifications and usage patterns. ### Class Boilerplate (BaseHandler anatomy) [#class-boilerplate-basehandler-anatomy] The D'fflib Trigger Handler Framework provides a structured way to handle trigger events in Salesforce, ensuring that logic is executed in a predictable and bulkified manner, where the trigger state is easily accessible. To allow registration, a handler class must extend `BaseHandler` and implement the appropriate [trigger event interfaces](/dfflib/docs/what/trigger-framework#trigger-event-coverage) for the events it supports (like `BeforeInsert`). This opens up the following three (optional `virtual`) methods for implementation: | Method | Purpose | | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ | | 1. `initialize(state, uow)` | Runs once. Retrieval of data or eligibility checks before processing the records. | | 2. `process(current, previous, uow)` | Runs per record. Perform logic and e.g. register to unit of work. **No SOQL or DML**. Return `true` if the record was processed, `false` to skip | | 3. `finalize(state, uow)` | Runs once. Wrapping up, logging, additional data retrieval or registration. | ```apex public inherited sharing class CalculateTotalPrice extends BaseHandler implements BeforeInsert, BeforeUpdate{ // Called once before record iteration — use for bulk queries and setup public override void initialize( TriggerState ts, dfflib_ISObjectUnitOfWork uow ){ // e.g. pre-load related records from a selector } // Called once per record — no SOQL, no DML public override Boolean process( SObject current, SObject original, dfflib_ISObjectUnitOfWork uow ){ RoomReservation__c newRecord = ( RoomReservation__c ) current; RoomReservation__c oldRecord = ( RoomReservation__c ) original; // register work on uow, return true if this record was processed return true; } // Called once after record iteration public override void finalize( TriggerState state, dfflib_ISObjectUnitOfWork uow ){ // e.g. call Domain method, Log } } ``` The D'fflib Trigger Handler Framework executes the methods of the registered handlers in a specific order: 1. All `initialize()` methods are called, to guarantee all setup or eligibility checks are performed on the original trigger state, before records are possibly modified 2. All `process()` methods are called for each record 3. All `finalize()` methods are executed. In pseudocode, this looks like: ```apex // initialize unit of work // loop over handlers handler.initialize( triggerState, uow ); // loop over handlers // loop over records handler.process( record, previousRecord, uow ); // loop over handlers handler.finalize( triggerState, uow ); // commit unit of work ``` Instead of handlers extending the `BaseHandler`, fflib provides overridable hooks in the Domain class. They hold all `records` of the transaction in one call, so looping, querying and registering is done in the same method. There are dispatchers that call these hooks in a specific order during the trigger execution. Despite the ability to override dispatchers, it's generally recommended to initially only override hooks for consistent behaviour. | Dispatcher | Hooks (in call order) | D'fflib equivalent | | ----------------------- | ----------------------------------------------------------------------- | ----------------------- | | `handleBeforeInsert()` | 1. `onApplyDefaults()`
2. `onBeforeInsert()` | `BeforeInsert` handler | | `handleBeforeUpdate()` | 1. `onBeforeUpdate()` | `BeforeUpdate` handler | | `handleBeforeDelete()` | 1. `onBeforeDelete()` | `BeforeDelete` handler | | `handleAfterInsert()` | 1. CRUD check (create)
2. `onValidate()`
3. `onAfterInsert()` | `AfterInsert` handler | | `handleAfterUpdate()` | 1. CRUD check (update)
2. `onValidate()`
3. `onAfterUpdate()` | `AfterUpdate` handler | | `handleAfterDelete()` | 1. CRUD check (delete)
2. `onAfterDelete()` | `AfterDelete` handler | | `handleAfterUndelete()` | 1. CRUD check (undelete)
2. `onAfterUndelete()` | `AfterUndelete` handler | * The CRUD check (step 0) only runs in the after dispatchers. It throws a `DomainException` when the user lacks the permission, unless disabled via `Configuration.disableTriggerCRUDSecurity()`. * Validation runs in the after phase, there is no validate hook before the DML.
*** ## Concepts and examples [#concepts-and-examples] ### Lifecycle flexibility [#lifecycle-flexibility] A trigger handler often requires two loops, one for collecting necessary data and another for processing the records. Therefore, there are multiple ways to implement the same business logic. In the use-case when needing to register work based on the parents' values, you can: * loop over records in `initialize()` to fetch parent-Ids, query; and then register in `process()` * loop over records in `process()`, and query and loop in `finalize()` There isn't a single correct approach. The choice depends on the specific requirements and the desired trigger behaviour. Which could be dependent on [need to share data across phases](#share-data-across-phases-and-handlers) or based on the eligibility by [trigger handler execution order](#trigger-handler-execution-order). Most commonly, all eligibility checks and data collection are done in `initialize()`. CalculateTotalPrice (initialize + process) ValidateDeactivation (process + finalize) ```apex title="DOM_RoomReservations.cls" repo="classes/DOM_RoomReservations.cls" public inherited sharing class CalculateTotalPrice extends BaseHandler implements BeforeInsert, BeforeUpdate, FireOnce{ private Map roomsById; public override void initialize( TriggerState state, dfflib_ISObjectUnitOfWork uow ){ Set roomIds = new Set(); // Loop Reservations to collect Room__c Ids for( Integer i = 0, j = state.currentList.size(); i < j; i++ ){ RoomReservation__c res = ( RoomReservation__c ) state.currentList[ i ]; if( res.Room__c != null ){ roomIds.add( res.Room__c ); } } // Query Rooms and group them by Id for easy retrieval roomsById = new Map( ( List ) SEL_Rooms.newInstance( dfflib_Database.Context.NONE ).selectSObjectsById( roomIds ) ); } public override Boolean process( SObject current, SObject previous, dfflib_ISObjectUnitOfWork uow ){ RoomReservation__c res = ( RoomReservation__c ) current; Room__c room = roomsById.get( res.Room__c ); if( room != null && res.CheckInDate__c != null && res.CheckOutDate__c != null ){ Integer nights = res.CheckInDate__c.daysBetween( res.CheckOutDate__c ); if( nights > 0 ){ res.TotalPrice__c = room.PricePerNight__c * nights; } } return true; } } ``` ```apex title="DOM_Rooms.cls" repo="classes/DOM_Rooms.cls" public inherited sharing class ValidateDeactivation extends BaseHandler implements BeforeUpdate, FireOnce{ Set deactivatedRoomIds = new Set(); // Collect the records that changed from active to inactive. // Since records should be checked for changed AND currently being inactive, // getChangedRecords() would cause a duplicate loop, therefore performing in process()-loop public override Boolean process( SObject current, SObject previous, dfflib_ISObjectUnitOfWork uow ){ Room__c curr = ( Room__c ) current; Room__c prev = ( Room__c ) previous; if( curr.IsActive__c == false && prev.IsActive__c == true ){ deactivatedRoomIds.add( curr.Id ); } return true; } // One aggregate query for all collected records, optionally adding errors public override void finalize( TriggerState state, dfflib_ISObjectUnitOfWork uow ){ if( deactivatedRoomIds.size() > 0 ){ List numOpenReservationsPerRoom = SEL_RoomReservations .newInstance( dfflib_Database.Context.NONE ) .selectOpenCountPerRoomId( deactivatedRoomIds ); Map roomsById = new Map( ( List ) state.currentList ); for( Integer i = 0, j = numOpenReservationsPerRoom.size(); i < j; i++ ){ dfflib_AggregateResult result = numOpenReservationsPerRoom[ i ]; Id roomId = ( Id ) result.get( 'Room__c' ); if( Integer.valueOf( result.get( 'numOpenReservations' ) ) > 0 ){ Room__c roomToSetError = roomsById.get( roomId ); roomToSetError.addError( 'Cannot deactivate a room with open reservations.' ); } } } } } ``` A hook is a single method: there are no separate phases. Collecting Ids, querying and processing the records all happen inside the one hook, in the order you write them. Keep queries outside the record loop, as in `initialize()`. Data shared between steps is held in local variables or fields on the Domain. The D'fflib phases make this structure explicit, and keep `process()` free of queries. {/** todo: when metadata is added ### Trigger disablement Use metadata to disable triggers selectively Leverage `getTriggerEvent(...).disableBeforeInsert()` to selectively disable the before insert trigger for specific conditions or records. ```apex //Disables the before insert portion of the trigger dfflib_SObjectDomain.getTriggerEvent(Cases.class).disableBeforeInsert(); //Code to execute while that trigger event is off //Re-enables the before insert portion of the trigger dfflib_SObjectDomain.getTriggerEvent(Cases.class).enableBeforeInsert(); ``` */} ### Trigger State [#trigger-state] The trigger framework constructs the Domain in the before phase. With `TriggerState` enabled, that same Domain instance is kept and reused in the after phase (with its `records` refreshed), instead of constructing a new one. Domain instance fields therefore survive from the before to the after phase, e.g. an expensive query result. The Domain is recursion-aware: when DML in a handler fires the trigger again, the nested invocation gets a fresh Domain instance, and the outer one is restored afterwards. The D'fflib Domain constructor `super( sObjectList, uow )` enables Trigger State. Only a Domain constructed with `super( sObjectList )` has it disabled. Handler instances are not kept: they are instantiated for every event execution, so handler fields only live within that one event. Trigger State is disabled by default. Without it, every trigger phase works on a new Domain instance, so a field set in `onBeforeInsert()` is empty in `onAfterInsert()`. Enable (or disable) it in the Domain constructor, directly after `super()`: ```apex public Rooms( List rooms ){ super( rooms ); Configuration.enableTriggerState(); // Configuration.disableTriggerState() to turn it off again } ``` ### Access control [#access-control] * For Selectors, the `dfflib_Database.Context` is specified upon selector initiation, like normal usage, thus in full control of the handler. * For Unit of Work, by default, every trigger handler shares the same instance injected by the framework, which is constructed upon Domain initialisation. All changes across all handlers commit in one transaction. There are two ways to control the context of the Unit of Work: 1. To control for all handlers at once, specify the Context in the Domain constructor ```apex public DOM_Rooms( List sObjectList ){ super( sObjectList, dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL ) ); // ... Handler registration } ``` 2. To deviate for only one Handler, control within that handler, by initiating a separate Unit of Work with the desired `dfflib_Database.Context`. Which implies, all transaction management, including Exception handling and commit becomes the handlers' responsibility. ```apex public without sharing class SyncProductMinMaxPrices extends BaseHandler implements BeforeInsert, BeforeUpdate, FireOnce{ private Map products; private final Set productIdsRequiringValidation = new Set(); private dfflib_ISObjectUnitOfWork uowSystemMode; // Gather Product IDs from trigger state records public override void initialize( TriggerState state, dfflib_ISObjectUnitOfWork uow ){ this.uowSystemMode = dfflib.unitOfWork.newInstance( dfflib_Database.Context.NONE ); Set productIds = new Set(); for( Integer i = 0, j = state.currentList.size(); i < j; i++ ){ productIds.add( ( ( ProductSupplierPrice__c ) state.currentList[ i ] ).Product__c ); } products = new Map( SEL_Products.newInstance( dfflib_Database.Context.NONE ) .selectSummaryPriceFieldsByIds( productIds ) ); } // Per-record logic — register dirty records to UoW public override Boolean process( SObject current, SObject previous, dfflib_ISObjectUnitOfWork uow ){ ProductSupplierPrice__c psp = ( ProductSupplierPrice__c ) current; Product2 parentProd = products.get( psp.Product__c ); // Validate whether new lowest price, if so, update on Parent Product if( parentProd.Min_Supplier_Purchase_Price__c == null || psp.Min_Supplier_Purchase_Price__c < parentProd.Min_Supplier_Purchase_Price__c ){ parentProd.Min_Supplier_Purchase_Price__c = psp.Min_Supplier_Purchase_Price__c; this.uowSystemMode.registerDirty( parentProd, new List{ Product2.Min_Supplier_Purchase_Price__c } ); } // ... Track products that require validation and add to productIdsRequiringValidation return true; } public override void finalize( TriggerState state, dfflib_ISObjectUnitOfWork uow ){ // Cross-Domain calls belong in finalize, after all records are processed if( !productIdsRequiringValidation.isEmpty() ){ DOM_Products.newInstance().validateMinMaxSupplierCurrencies( productIdsRequiringValidation, this.uowSystemMode ); } try{ this.uowSystemMode.commitWork(); } catch( Exception e ){ // Handle exception as needed } } } ``` It's best-practice to always declare a sharing mode for classes, and also for the (inner) trigger handler classes. When a Unit of Work is run with `System Mode`, it will still respect the sharing mode of the class in which it is executed. By declaring the sharing mode explicitly, it is clearer under which context the database transactions are expected. Since the trigger hooks live within the Domain, there is no distinction between the Domain and its handlers in terms of access control. However, there is one mechanism to optionally bypass the object-permission (CRUD) checks of the after hooks, by calling `Configuration.disableTriggerCRUDSecurity()` in the Domain constructor. This can only be disabled per SObjectType and not per dispatcher or hook. ### Share data across phases and handlers [#share-data-across-phases-and-handlers] Within one handler, instance variables carry data across the phases (`initialize`, `process`, `finalize`), as [`ValidateDeactivation`](#lifecycle-flexibility) does with `deactivatedRoomIds` or `SyncProductMinMaxPrices` with `products` and `uowSystemMode`. This avoids static state and additional queries. Handlers of the same trigger event can build on each other's record changes, but mind the [execution order](#trigger-handler-execution-order) of the framework. If a handler changes a value on a TriggerState record, the next handler will automatically see the change. Handlers hold no reference to each other, so data other than the records themselves has to be exchanged through a shared holder, e.g. a static member on the Domain class, which is best kept to a minimum. ### Detect changed records [#detect-changed-records] In an update trigger every record of the transaction reaches your handler, whether or not the fields you care about were touched. The Domain's `getChangedRecords()` narrows the scope to the records where at least one of the given fields differs from its previous value, so downstream queries and loops only run when needed. It's available to both D'fflib handlers and fflib hooks, since it is a method of `dfflib_SObjectDomain` itself. ```apex title="Illustrative" public override void initialize( TriggerState state, dfflib_ISObjectUnitOfWork uow ){ List changedRooms = ( List ) getDomain().getChangedRecords( new Set{ Room__c.IsActive__c } ); // Query and prepare only for changedRooms } ``` While it is recommended to pass a strongly typed set of `SObjectField`s to `getChangedRecords()`, the method also accepts a set of field names as strings. Inside a hook the method is called directly on the Domain and not from a handler sub-class. Therefore there is no need to call `getDomain()`: ```apex public override void onBeforeUpdate( Map existingRecords ){ List changedRooms = ( List ) getChangedRecords( new Set{ Room__c.IsActive__c } ); } ``` ### Add record errors [#add-record-errors] In Apex, it is possible to add an error to a record programmatically using the `addError()` methods. This prevents the record from being saved: with the default all-or-none DML, the whole operation fails. Note, the specified String or Exception will be directly shown to the end-user, so using custom labels for translations etc. is recommended. ```apex [record].addError( 'Lovely error message.' ); [record].addError( 'Lovely error message.', false ); // skip escape, to render HTML in UI try{ // some code that might throw an exception } catch( Exception ex ){ [record].addError( ex ); } ``` ```apex title="DOM_RoomsTest.cls" repo="classes/DOM_RoomsTest.cls" List errors = currentRoom.getErrors(); System.Assert.areEqual( 1, errors.size(), 'Expected 1 error for room with open reservations' ); System.Assert.areEqual( 'Cannot deactivate a room with open reservations.', errors[ 0 ].getMessage(), 'Expected different error message' ); ``` Despite `addError()` methods existing since Spring '08 (API 12.0), Salesforce only supported asserting errors per Winter '21 (API 50.0), by adding `getErrors()` and `hasErrors()` to SObject. With this introduction, the supporting error registry in `dfflib_SObjectDomain` has become obsolete and is marked `@deprecated`. It's encouraged to move away from `[record].addError( error( 'Some error message', [record] ) )` and `dfflib_SObjectDomain.Errors.getAll()`. ### FireOnce [#fireonce] Handlers that implement FireOnce are only executed once per record per transaction. For records where `process()` returns `true`, this is skipped on any subsequent trigger invocation within the same transaction, e.g. for when the same record would be triggered again via another trigger, Flow or own DML. ```apex public inherited sharing class CalculateTotalPrice extends BaseHandler implements BeforeInsert, BeforeUpdate, FireOnce{ // ... } ``` Notes: * `FireOnce` is tracked per handler-event combination. Thus if one handler is set for both before and after events, it will track separately for each event. * `FireOnce` is only tracked within one transaction, implying that each transaction will start fresh and process all records. * When all records have been processed, the full handler will be skipped, including `initialize()` and `finalize()`. * When re-evaluation is needed for potential eligibility-revisits due to field-changes, return `false` or don't implement `FireOnce` for that handler. *** ## Testing a Trigger [#testing-a-trigger] See the [Testing & Mocking](/dfflib/docs/how/testing-mocking) article for full details on setting up mocks, stubs, and ApexMocks used across all layers. **Trigger**\ In a codebase which fully adopted (D')fflib, SObjects might not be inserted or updated during unit tests. When such SObjects do have a trigger implemented, these triggers will have a 0% test coverage and thus cause deployments to fail. While we're defensive on adding code "just for the sake of code coverage", for this situation we either recommend to add an end-to-end unit test, or create one class which only performs inserts for all SObjects with a trigger, to prevent unexpected deployment failures. Like [TriggersTest](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/TriggersTest.cls). **Handler**\ The framework provides `runHandler()` to execute a specific handler for a given trigger event in isolation. Implying no construction of Domain, trigger execution or DML. ```apex title="DOM_RoomReservationsTest.cls" repo="classes/DOM_RoomReservationsTest.cls" @IsTest private static void calculateTotalPrice_validRoomAndDates(){ // create mocks fflib_ApexMocks mocks = new fflib_ApexMocks(); dfflib_ISObjectUnitOfWork uowMock = dfflib.unitOfWork.defineMock( mocks ); SEL_Rooms m_selRooms = ( SEL_Rooms ) dfflib.selector.defineMock( mocks, SEL_Rooms.class, Room__c.SObjectType ); // Given - Room with PricePerNight = 42.0 and Reservation for 3 nights DOM_RoomsTest.Builder roomBuilder = TestFactory.aRoom().asSingleRoom( 101 ); RoomReservation__c res = ( RoomReservation__c ) TestFactory.aRoomReservation() .asDefault() .forRoom( roomBuilder ) .withDates( Date.today(), Date.today().addDays( 3 ) ) .mockWithIds(); Room__c room = ( Room__c ) roomBuilder.mockWithIds(); // set mocks mocks.startStubbing(); mocks.when( m_selRooms.sObjectType() ).thenReturn( Room__c.SObjectType ); mocks.when( m_selRooms.selectSObjectsById( new Set{ res.Room__c } ) ) .thenReturn( new List{ room } ); mocks.stopStubbing(); // When - Run the CalculateTotalPrice handler for BEFORE_INSERT new DOM_RoomReservations( new List{ res } ).runHandler( DOM_RoomReservations.CalculateTotalPrice.class, dfflib_SObjectDomain.TriggerEvent.BEFORE_INSERT, null, uowMock ); // Then - TotalPrice should be PricePerNight (42.0) x 3 nights = 126.0 System.Assert.areEqual( 126.0, res.TotalPrice__c, 'Expected TotalPrice = PricePerNight x nights' ); } ``` For update events, the previous records can be passed as third argument (`Map oldMap`), like in [`DOM_RoomsTest`](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/DOM_RoomsTest.cls). To assert hook-execution and logic in fflib, you can leverage the `MockDatabase`, which emulates a DML operation without performing it. **How it works** 1. **Seed** the mock via `fflib_SObjectDomain.Test.Database`: `onInsert( records )`, `onUpdate( records, oldRecords )`, `onDelete( recordsById )` or `onUndelete( records )`. Each call selects one operation and clears the flags of the others. 2. **Invoke** `fflib_SObjectDomain.triggerHandler( DOM_Rooms.class )`, the exact call the trigger makes. In a test with seeded records it reads the mock instead of `Trigger.new`/`Trigger.oldMap`. 3. **Replay**: the framework constructs the Domain via its `Constructor`, then runs the before phase and the after phase back to back on the seeded records. 4. **Assert** on the records, e.g. defaults applied in the before phase, or errors via `getErrors()`. For updates, `existingRecords` (and with that `getChangedRecords()`) is served from the old records given to `onUpdate()`. ```apex @IsTest private static void onValidate_inactiveRoom(){ // Given - set data Room__c current = new Room__c(); current.Id = fflib_IDGenerator.generate( Room__c.SObjectType ); current.Capacity__c = 1; current.IsActive__c = true; current.Name = 'ROOM-00101'; current.PricePerNight__c = 40.2; current.RoomType__c = DOM_Rooms.TYPE_SINGLE; Room__c previous = current.clone( true ); current.IsActive__c = false; // set mocks fflib_SObjectDomain.Test.Database.onUpdate( new List{ current }, new Map{ previous.Id => previous } ); // When - invoke the trigger handler fflib_SObjectDomain.triggerHandler( DOM_Rooms.class ); // Then - assert expectation System.Assert.isTrue( current.getErrors().isEmpty(), 'Expected no errors because of inactive room' ); } ``` **Pitfalls** * Nothing is persisted: no Ids are assigned and no before-save changes are applied beyond your handler logic. Seed records with (mocked) Ids when updating or deleting. * The mock keeps the state of earlier calls: `onInsert()` does not clear previous old records and `onDelete()` does not clear previous records. Use one scenario per test method. * While the mock holds records, every `triggerHandler()` call in that test uses it, so real DML in the same test does not run the real trigger path. * The after-phase CRUD check applies to the running test user, and events disabled via `getTriggerEvent()` are skipped. * Triggers are not covered by this approach; the single real DML in [`TriggersTest`](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/TriggersTest.cls) remains required. * Dependencies of the Domain (Unit of Work, selectors) still need to be mocked, see [Testing & Mocking](/dfflib/docs/how/testing-mocking). | | `runHandler()` | `MockDatabase` | | -------------- | ------------------------------ | ----------------------------------------------------------------------------- | | Scope | One registered D'fflib handler | Whole Domain: hooks, dispatchers and registered handlers | | Trigger events | One chosen event | Before and after phase of the seeded operation | | Typical use | Handler logic | Hook-based Domains, `getChangedRecords()`, end-to-end Domain flow without DML | *** ## Migration steps [#migration-steps] Both fflib hooks and D'fflib handlers can coexist, though it's recommended to apply consistency and choose one trigger construct. To migrate existing fflib hooks to D'fflib handlers to untangle nested logic and fully adopt the D'fflib approach, follow the steps outlined below. **Trigger** 1. Change reference from `fflib_SObjectDomain` to `dfflib_SObjectDomain`. Since this is backward compatible, this can be done without an immediate change to the existing hook- and dispatcher-overrides. ```apex dfflib_SObjectDomain.triggerHandler( DOM_Rooms.class ); ``` **Domain enabler** 1. Ensure Domain extends D'fflib, as documented in [Domains migration guide](/dfflib/docs/how/domains#migration-steps). 2. Enable Trigger Handler Framework Extend the `super( SObjectList )` in the Domain constructor with a Unit of Work instance. This gives control to define the desired `dfflib_Database.Context` for all Trigger Handler DML operations. Additionally, this instructs the Domain to enable the Handler Framework, like `enableTriggerState()`, which improves performance by keeping the Domain instance consistent across Trigger Events. ```apex public DOM_Rooms( List sObjectList ){ // Initialize the domain super( sObjectList, dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL ) ); // ... Handler registration } ``` **Hook to handler migration** 1. Pick one `on*` hook or dispatcher override in the Domain\ Preferably one that has grown large or is hard to test. 2. Create a handler class named after its single-responsibility, extending `BaseHandler` and implementing the event interface (e.g. `BeforeInsert`) and `FireOnce` when desired. 3. Move the logic into the handler\ The record loop becomes `process()`, queries move to `initialize()`, and DML becomes registration on the injected Unit of Work. Optionally prefix `getDomain().` to reference Domain methods like `getChangedRecords()`. 4. Add `registerHandler( TriggerEvent., .class )` to the Domain constructor and remove the hook override Note, this can only be done when the Domain has [been migrated](/dfflib/docs/how/domains#migration-steps), and thus extends the D'fflib `dfflib_SObjectDomain`. **Test class changes** 1. Replace the `MockDatabase` test of the migrated hook with a `runHandler()` test 2. Keep one real DML test for the Trigger itself, see [Trigger coverage](/dfflib/docs/how/testing-mocking#trigger-coverage) --- # Unit of Work URL: /dfflib/docs/how/unit-of-work/ Step-by-step guide on how to set up and interact with the Unit of Work, maximise the functions and benefits, while being aware of edge cases and D'fflib-specific functionalities. ## Characteristics [#characteristics] The Unit of Work is a utility to simplify and centralise all database interactions, including transaction, exception and rollback management. It improves performance and helps avoid exceeding governor limits, while keeping the code clean and readable. Think of it as a shopping cart which is passed along; each layer can add items, but checkout is controlled by the caller, and performed in a bulkified manner. ### Responsibilities [#responsibilities] The Unit of Work centralises all DML operations into a single transaction boundary: Separate database interactions from business logic Bulkify DML operations by bundling and executing one operation per SObject and DML action combination Manage transactions and rollbacks: automatically generate savepoints and roll back upon failure to keep the database consistent, centralising repetitive code Simplify registration of related records in a readable and clean manner ### Interactions [#interactions] | Interaction | Layers | | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | Called by (Initiation and commit) | Entrypoints, including the Domain for Triggers and isolated Services (like incoming APIs), and Trigger Handlers with a deviating Context | | Usage (Register to provided instance) | Domains, Trigger Handlers, Services | | Calling | None. The Unit of Work never calls any other layer or service | Typically, a Unit of Work is initiated by an Entrypoint (which owns and controls the transaction), and is passed to other layers to register record modifications to. Like the creation in a Domain constructor, to be passed into every handler phase, or the construction in a Batch or incoming API Service. These Entrypoints are responsible for handling exceptions and properly logging failures. ### Rules [#rules] * Always instantiate a Unit of Work with an explicit `dfflib_Database.Context`, rather than relying on the default `INHERIT`. * Never instantiate or commit a Unit of Work outside of Entrypoints. Other layers should only receive a Unit of Work as a parameter. (Exception for Domains with specific Trigger Handler needs) * Avoid creating multiple Unit of Work instances in one transaction. Be critical whether truly needed. * When looping records, register within the loop, rather than in bulk after the loop, to avoid an additional loop within the Unit of Work. *** ## Initiation [#initiation] ### How to call [#how-to-call] There are different method overloads for instantiating a Unit of Work, to meet the possible business needs. ```apex // Default: metadata-driven SObject sequence, default INHERIT Database Context dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance(); // Apply explicit Database Context, metadata-driven SObject sequence dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL ); // Apply deviating SObjects, e.g. for non-registered SObjects, or deviating sequence, default Context dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( new List{ Room__c.SObjectType, RoomReservation__c.SObjectType } ); // Apply explicit SObject sequence and Database Context dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( new List{ Room__c.SObjectType, RoomReservation__c.SObjectType }, dfflib_Database.Context.NONE ); ``` With an explicit `List` only those SObjectTypes are allowed: registering a record of any other type throws an exception. ### Metadata registration [#metadata-registration] When no List of SObjectTypes is provided, `newInstance()` uses `Dfflib_UOW_Config__mdt` to determine the SObject DML sequence. | Field | Purpose | | ---------------- | -------------------------------------------------------------------------------------------- | | `DeveloperName` | Unique API name of the record, by convention the SObject API name with `__c` written as `_c` | | `MasterLabel` | Label of the record, as shown in Setup | | `SObjectType__c` | API name of the SObject in the sequence | | `SortOrder__c` | DML execution order, sequential order for insert/update/undelete and reverse for delete | Order matters to satisfy SObject dependencies. Parents must be inserted before children, and deleted after. `RoomReservation__c` looks up both `Contact` and `Room__c`, so it should have a higher `SortOrder__c`; otherwise the Contact might not be inserted yet when the reservation is inserted. | `SObjectType__c` | `SortOrder__c` | | -------------------- | -------------- | | `Contact` | 10 | | `Room__c` | 20 | | `RoomReservation__c` | 30 | *** ## Anatomy (how it works) [#anatomy-how-it-works] In essence, the Unit of Work is just a collection of simple maps that track records per operation and SObjectType combination, and orchestrates their persistence in a bulkified and transactional manner. **Keeping registered records and configurations in memory** ```apex List m_sObjectTypes; Map> m_newListByType; Map> m_relationships; Map m_newDmlOptions = new Map(); ``` **Registrations**\ The single-responsibility of registration methods is to validate input and store the values in the corresponding map. ```apex public void registerNewDmlOptions( Schema.SObjectType sType, Database.DMLOptions options ){ m_newDmlOptions.put( sType, options ); } ``` ```apex public void registerNew( SObject record, Schema.SObjectField relatedToParentField, SObject relatedToParentRecord ){ // Record-validations like an insert not having an Id (yet), but update and delete requiring an Id validateRecordForDMLAction( record, DMLActions.dNEW ); // Check whether this SObjectType was already registered, else initialise list in correct sequence // Validating whether SObjectType is supported for the requested DML action (no publish for an Account) Schema.SObjectType sObjType = record.getSObjectType(); if( !m_newListByType.containsKey( sObjType ) ){ implementSObjectType( sObjType, DMLActions.dNEW ); } m_newListByType.get( sObjType ).add( record ); if( relatedToParentRecord != null && relatedToParentField != null ){ registerRelationship( record, relatedToParentField, relatedToParentRecord, DMLActions.dNEW ); } } ``` **commitWork() and its fixed sequence** Like the registration methods, no rocket science happens in the `commitWork()`. It simply iterates over the registered records and relationships in a fixed sequence and performs the corresponding DML operations. Below is a simplified representation of this sequence, with D'fflib extensions highlighted. ```apex title="Simplified representation of commitWork()" // Return when no work is registered // [!code highlight] // Reset SaveResults of possible previous commitWork() // [!code highlight] // Set Savepoint (skipped in tests) try{ // Publish "before" Platform Events // Priority inserts // [!code highlight] // Priority updates // [!code highlight] // Priority upserts // [!code highlight] // Priority deletes - in reverse order // [!code highlight] // Immediate inserts // [!code highlight] // Inserts // Immediate updates // [!code highlight] // Upserts // Updates // Immediate deletes - in reverse order // [!code highlight] // Deletes - in reverse order // Undeletes // [!code highlight] // Empty Recycle Bin - in reverse order // Send Emails and Approval Processes // [!code highlight] // IDoWork // Validate all Relationships were resolved, or throw Exception // [!code highlight] } catch( Exception e ){ // Roll back to the Savepoint // Rethrow the Exception } finally{ // Publish "after success" or "after failure" Platform Events // Reset all registered work to avoid accidental duplicate processing // [!code highlight] } ``` While matching methods have the same behaviour in both implementations, the internals differ. In fflib: * SObject sequence comes from the Application class, instead of metadata. * Maps are initialised for all configured SObjectTypes, not only for registrations. * Maps are stored per String instead of SObjectType, requiring casts. * Maps are kept even after the work has been committed, instead of reset. * Relationships are per SObjectType, instead of per SObjectType-DMLAction combination. * Savepoints are always set, and not excluded in unit tests. * Advanced steps like resolving email relationships are cast to `IDoWork`. * Several methods and hooks are virtual and can be overridden for extensions. The base sequence of `commitWork()` matches D'fflib, without the D'fflib extensions. Note that fflib sends emails after `IDoWork`, while D'fflib sends them before. ```apex public void commitWork(){ // Set Savepoint try{ // Publish "before" Platform Events // Inserts // Upserts // Updates // Deletes - in reverse order // Empty Recycle Bin - in reverse order // Resolve Email Relationships // IDoWork // Email work as last item } catch( Exception e ){ // Roll back to the Savepoint // Rethrow the Exception } finally{ // Publish "after success" or "after failure" Platform Events } } ``` *** Click for the full overview of the method differences between D'fflib and fflib. *** ## Standard methods [#standard-methods] ### Access control (Context) [#access-control-context-] The [Database Context](/dfflib/docs/what/database-context#database-context-enum) determines the sharing and permission model applied to all DML during `commitWork()`. It can be set at [construction](#how-to-call) and possibly overridden with `setContext()`. The Context is applied at `commitWork()`, so it covers all work registered before and after calling `setContext()`. Therefore, it's recommended to set this at construction, for ease of future maintainers. ```apex dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance(); // default INHERIT Database Context uow.setContext( dfflib_Database.Context.FULL ); // override the Context after construction ``` fflib has no `setContext()`. A deviating sharing and permission model requires an `IDML` implementation to be passed to the constructor. This can be a project-specific custom `IDML` implementation, or one of the out-of-the-box `SimpleDML` or `UserModeDML` implementations. ```apex // Apply explicit SObject sequence and IDML fflib_ISObjectUnitOfWork uow = [Application].unitOfWork.newInstance( new List{ Room__c.SObjectType, RoomReservation__c.SObjectType }, new fflib_SObjectUnitOfWork.UserModeDML() ); ``` D'fflib replaces these constructions with the Database Context: the matching `IDML` is resolved internally, so no project-specific `IDML` is needed. `UserModeDML` → `FULL`. `SimpleDML` → `INHERIT`. While migrating, an existing `IDML` can still be passed, see [Running a legacy fflib IDML](#running-a-legacy-fflib-idml). ### Standard registrations [#standard-registrations] Each standard registration method accepts both singular and bulkified input parameters. For new and updated records, an overload is available to directly register a relationship while registering the record. | Method | `SObject` | `List` | Relationship | | --------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | | `registerNew` (insert) | | | | | `registerDirty` (update) | | | | | `registerDeleted` (delete) | | | | | `registerEmptyRecycleBin` (remove from recycle bin) | | | | | `registerPermanentlyDeleted` (delete and remove from bin) | | | | | `registerUndeleted` (undelete) | | | | For example, cancelling reservations by updating only their status ([`cancelReservations`](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/CTRL_RoomReservations.cls#L109)): ```apex title="CTRL_RoomReservations.cancelReservations" repo="classes/CTRL_RoomReservations.cls#L109" 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(); ``` **Update specific fields (dirtyFields)** Sometimes the backend receives a full record with most fields populated, while it's unknown whether those match the database, and only one field should be updated. Either instantiate a new record with only the Id and the changed field (like the example above), or call `registerDirty` passing a `List`. * Instead of the passed record, the Unit of Work registers a clean `new SObject( Id )` holding only the listed fields. * Repeated calls for the same `Id` enrich the same registered record: field lists are merged, not replaced. * No reference to the input record is kept: changes made to it after registration are ignored until `registerDirty( record, dirtyFields )` is called again. * Calling `registerDirty( record )` without fields after a `dirtyFields` registration of the same record throws an exception, as the Unit of Work can't determine what to update. * It is possible to `registerDirty` by `dirtyFields`, when the record has no `Id` set yet. See [lifecycle edge cases](#lifecycle). | Signature | Purpose | | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- | | `registerDirty( SObject record, List dirtyFields )` | Single record | | `registerDirty( List records, List dirtyFields )` | Bulk, same fields for every record | | `registerDirty( SObject record, List dirtyFields, SObjectField relatedToParentField, SObject relatedToParentRecord )` | Single record with relationship | ```apex // single record, two fields to update uow.registerDirty( room, new List{ Room__c.PricePerNight__c, Room__c.IsActive__c } ); // bulk records, one field to update uow.registerDirty( rooms, new List{ Room__c.PricePerNight__c } ); // single record, one field to update, with relationship uow.registerDirty( roomReservation, new List{ RoomReservation__c.Status__c }, RoomReservation__c.Room__c, room ); ``` *** ### Lifecycle [#lifecycle] There are a couple of tricks and caveats in the setup of the Unit of Work that help when you know them. * Salesforce Id automatically set after insert * Local assignments to an already registered record * Insert and update record in same Unit of Work * Continue using the same Unit of Work **Salesforce Id automatically set after insert** Like in standard Apex, and because of keeping track of references, the Salesforce Id is automatically set on the record after it is inserted. This implies you can continue working with the registered record and also enables the Unit of Work to [resolve relationships](#relationships) within one `commitWork()`. **Local assignments to an already registered record** When you make changes to an already registered record, you don't need to `registerDirty` again, as the reference is tracked. This does not apply to `dirtyFields` registrations, which register a clean copy. This implies you should be conscious when modifying records in Apex in between registration and committing the Unit of Work. ```apex // Process new reservation and register for insertion RoomReservation__c roomReservation = new RoomReservation__c( Status__c = DOM_RoomReservations.STATUS_SUBMITTED, ... ); uow.registerNew( roomReservation ); // Perform additional logic, like validating Payment status roomReservation.Status__c = DOM_RoomReservations.STATUS_PAID; // Save to the database. Due to the reference being tracked, the record will be inserted with 'PAID' status. uow.commitWork(); ``` **Insert and update record in same Unit of Work** It is possible to insert a record and then update it within the same Unit of Work, even with registration via `dirtyFields`. The Unit of Work generates an internal identifier to match relationships and to ensure the correct sequence of operations. However, for validations to pass it is important to call `registerNew` before `registerDirty`. ```apex // Register new room Room__c room = new Room__c( Name = 'Deluxe Suite', PricePerNight__c = 200 ); uow.registerNew( room ); // Update record to e.g. trigger an external integration; // Be conscious not to modify the original record, as the change would then already be included in the insert uow.registerDirty( room ); ``` **Continue using the same Unit of Work** To enable reusing the same Unit of Work, `commitWork()` automatically resets all registrations afterwards, both after success and after failure (`resetWork()` ). SaveResults are reset at the start of the next `commitWork()`, as otherwise you wouldn't be able to fetch the results after `commitWork()` completion. Both can also be called manually: `uow.resetWork()` and `uow.resetSaveResults()`. This could be useful when needing isolated transactions, or e.g. to register a Log after completion, based on success or failure. ```apex dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL ); uow.registerNew( rooms ); uow.commitWork(); // registrations are reset automatically uow.registerDirty( reservations ); uow.commitWork(); // the rooms are not inserted again ``` | Reset after `commitWork()` | Kept after `commitWork()` | | --------------------------------------------------------- | ------------------------------------------ | | Registered records, events, emails and approval processes | Database Context | | Relationships | SObjectTypes provided at construction | | DML options and AllOrNone | SaveResults, until the next `commitWork()` | | Registered `IDoWork` | | The automatic reset runs in the `finally` of `commitWork()`. When an exception is thrown *before* `commitWork()` is called, those registrations remain. Reusing that Unit of Work, e.g. to insert a log, would also insert the previously registered Contacts. Thus, when reusing a Unit of Work in a `finally` block, it is important to explicitly reset the work before registering new operations. ```apex title="SRVi_RoomReservations.handleRequest" repo="classes/SRVi_RoomReservations.cls" try{ ... uow.commitWork(); } catch( ... ){ ... } finally{ // Optionally, log the request for auditing purposes based on the set Response // Allowing reuse of the same Unit of Work to e.g. publish a Platform Event // Reset explicitly to ensure when an Exception is thrown before commitWork(), the previously registered work is reset as well // uow.resetWork(); } ``` *** ### DML options and AllOrNone [#dml-options-and-allornone-] To meet the business requirements, you sometimes need to specify DML options or the `allOrNone` behaviour. Define per SObjectType which options apply. ```apex // DML options for insert and update registerNewDmlOptions( SObjectType sType, Database.DMLOptions options ) registerDirtyDmlOptions( SObjectType sType, Database.DMLOptions options ) // AllOrNone options for most DML operations registerNewAllOrNone( SObjectType sType, Boolean allOrNone ) registerDirtyAllOrNone( SObjectType sType, Boolean allOrNone ) registerDeletedAllOrNone( SObjectType sType, Boolean allOrNone ) registerUndeletedAllOrNone( SObjectType sType, Boolean allOrNone ) registerUpsertedAllOrNone( SObjectType sType, Boolean allOrNone ) ``` ```apex Database.DMLOptions options = new Database.DMLOptions(); options.duplicateRuleHeader.allowSave = true; uow.registerNewDmlOptions( RoomReservation__c.SObjectType, options ); uow.registerDirtyDmlOptions( RoomReservation__c.SObjectType, options ); uow.registerNewAllOrNone( RoomReservation__c.SObjectType, false ); // continue past failing records ``` * Setting `allOrNone = false` enables SaveResults automatically, see [SaveResults](#saveresults-). * Immediate operations are not affected by DML options or AllOrNone. * Options are reset after `commitWork()`: register them again when reusing the Unit of Work. *** ### Platform Events [#platform-events] | Method | `SObject` | `List` | Publication moment | | ---------------------------------------- | :-----------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------: | --------------------------------------- | | `registerPublishBeforeTransaction` | | | First, before any DML | | `registerPublishAfterSuccessTransaction` | | | Last, only when all work succeeded | | `registerPublishAfterFailureTransaction` | | | Last, only after a failure and rollback | ```apex // Register standard event publication before any DML uow.registerPublishBeforeTransaction( new BatchApexErrorEvent() ); // Register custom event to publish only when the commit succeeds uow.registerPublishAfterSuccessTransaction( new AsyncProcess__e() ); // Register custom event to publish only when the commit fails uow.registerPublishAfterFailureTransaction( new AsyncProcess__e() ); ``` * fflib supports custom events; D'fflib also allows standard platform events to be published . * Registering a record that is not an event throws an exception. * After a DML failure, the exception is rethrown. To ensure the event is not rolled back, it's important to configure *Publish Immediately* on the custom platform event instead of *Publish After Commit*. *** ### Relationships [#relationships] Inserting a collection of parents and children in one transaction meant map complexity before fflib. It's impossible to separate concerns as you'll construct the parent and child records in memory, followed by a try-catch statement for the DMLs. But in that try-catch block, you'll also need to assign the parent Id to each child's lookup. Thus, scattered logic, mixing business and operational scope. The Unit of Work takes this over: register the parent, child and the relationship, even while the parent has no `Id` yet, and let `commitWork()` resolve the relationship "just in time". It keeps track of the reference in an internal map and, just before the child's DML, resolves the relationship and assigns the parent's Id. D'fflib No (D')fflib ```apex title="SRVi_RoomReservations.handleRequest" repo="classes/SRVi_RoomReservations.cls" dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL ); List bookings = payload.bookings; // Query contacts based on email Map contactsByEmail = matchGuests( bookings ); // Process each booking and populate output variable List reservations = new List(); for( Integer i = 0, j = bookings.size(); i < j; i++ ){ Wrapper_Booking booking = bookings[ i ]; // Validate whether Contact exists for guest email, or create new one String key = booking?.guest?.email?.toLowerCase(); Contact c = contactsByEmail.get( key ); if( c == null ){ c = booking.guest.convertToContact(); // Registered in the map, so multiple reservations of the same new guest share one Contact contactsByEmail.put( key, c ); uow.registerNew( c ); } // Create reservation and register for insertion // Register relationship between reservation and Contact, regardless of Contact.Id already known, or pending insertion RoomReservation__c reservation = booking.reservation.convertToReservation(); uow.registerNew( reservation, RoomReservation__c.Contact__c, c ); // [!code highlight] reservations.add( reservation ); } // Commit work to insert Contacts, resolve relations on RoomReservation__c and insert the reservations uow.commitWork(); ``` ```apex List bookings = payload.bookings; // Query contacts based on email Map contactsByEmail = matchGuests( bookings ); // Keep track of records to insert, to allow one transaction List contactsToInsert = new List(); List reservationsToInsert = new List(); // Contact instance per reservation, aligned by index; a new Contact has no Id yet, but receives it on insert, // so the lookup is resolved from the same instance afterwards List contactPerReservation = new List(); for( Integer i = 0, j = bookings.size(); i < j; i++ ){ Wrapper_Booking booking = bookings[ i ]; String key = booking?.guest?.email?.toLowerCase(); Contact c = contactsByEmail.get( key ); if( c == null ){ c = booking.guest.convertToContact(); // Registered in the map, so multiple reservations of the same new guest share one Contact contactsByEmail.put( key, c ); contactsToInsert.add( c ); } contactPerReservation.add( c ); reservationsToInsert.add( booking.reservation.convertToReservation() ); } // Manage the transaction manually, so a failing reservation insert does not leave orphan Contacts Savepoint sp = Database.setSavepoint(); try{ // Insert the Contacts first, as their Ids are required for the reservation lookup Database.insert( contactsToInsert, true, AccessLevel.SYSTEM_MODE ); // Resolve the lookup from the aligned Contact instance, now holding an Id for both existing and new guests for( Integer i = 0, j = reservationsToInsert.size(); i < j; i++ ){ reservationsToInsert[ i ].Contact__c = contactPerReservation[ i ]?.Id; } Database.insert( reservationsToInsert, true, AccessLevel.SYSTEM_MODE ); } catch( Exception ex ){ if( sp != null ){ Database.rollback( sp ); } // Rethrow, so the original exception type is mapped to a response below throw ex; } ``` As you can see, there's no need for maps and other logic to keep the records referenced and recognised. Especially when the parents don't have Ids yet, this can be rather cumbersome. With the above structure, it doesn't matter whether the parent (Contact) already existed or was pending insertion (new guest): the highlighted registration is identical for both. Relationships are typically registered inline (see [Standard registrations](#standard-registrations)), or with `registerRelationship`: | Signature | Purpose | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | | `registerRelationship( SObject record, SObjectField relatedToField, SObject relatedTo )` | Resolve the lookup to a parent record, registered in the same Unit of Work or already existing | | `registerRelationship( SObject record, SObjectField relatedToField, SObject relatedTo, DMLActions specificDMLAction )` | Same, restricted to one DML action | | `registerRelationship( SObject record, SObjectField relatedToField, SObjectField externalIdField, Object externalId )` | Resolve the lookup by an external Id value, without a parent record | | `registerRelationship( SObject record, SObjectField relatedToField, SObjectField externalIdField, Object externalId, DMLActions specificDMLAction )` | Same, restricted to one DML action | | `registerRelationship( Messaging.SingleEmailMessage email, SObject relatedTo )` | Populate the email `WhatId`, equal to `registerEmail( email, relatedTo )` | | `registerRelationship( Approval.ProcessRequest process, SObject relatedTo )` | Populate the `ObjectId` (submit request) or `WorkitemId` (workitem request), equal to `registerApprovalProcess( process, relatedTo )` | ```apex // Register multiple relationships to the same record uow.registerNew( reservation, RoomReservation__c.Contact__c, c ); uow.registerRelationship( reservation, RoomReservation__c.Room__c, room ); // Restrict the relationship to a specific DML action uow.registerRelationship( reservation, RoomReservation__c.Room__c, room, dfflib_SObjectUnitOfWork.DMLActions.dNEW ); // 'd' prefix, as NEW and INSERT are reserved words // Resolve the lookup by an external Id value instead of a record uow.registerRelationship( reservation, RoomReservation__c.Contact__c, Contact.External_Id__c, 'abc123' ); ``` * `registerDirty` with relationship accepts a record without `Id` when it is registered for insert in the same Unit of Work, supporting 1:1 constructions like a parent lookup to a child inserted in the same transaction . * A relationship is resolved once, at the first DML action that processes the record (upserts included). Pass a `DMLActions` value (`dNEW`, `dUPDATE`, `dUPSERT`, `dDELETE`) to bind it to a specific action, e.g. when the record is registered for multiple actions . * An unresolved relationship (e.g. the child was never registered for DML) throws an exception at the end of `commitWork()` . *** ## Advanced methods [#advanced-methods] ### Approval Process [#approval-process-] | Signature | Purpose | | ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | `registerApprovalProcess( Approval.ProcessRequest approvalProcess )` | Submit, approve or reject an approval process | | `registerApprovalProcess( Approval.ProcessRequest process, SObject relatedTo )` | Same, populating the `ObjectId` (submit request) or `WorkitemId` (workitem request) from the related record | Approval processes are processed after all DML, so the related record may be inserted by the same Unit of Work. ```apex Approval.ProcessSubmitRequest request = new Approval.ProcessSubmitRequest(); request.setComments( 'Group reservation exceeds the room capacity' ); uow.registerNew( reservation ); uow.registerApprovalProcess( request, reservation ); // ObjectId populated after the insert uow.commitWork(); ``` ### Email [#email] | Signature | Purpose | | -------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | `registerEmail( Messaging.Email email )` | Send any email after all DML | | `registerEmail( Messaging.SingleEmailMessage email, SObject relatedTo )` | Same, populating the `WhatId` from the related record, as only a `SingleEmailMessage` supports a `WhatId` | ```apex Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); email.setTargetObjectId( contactId ); email.setTemplateId( confirmationTemplateId ); uow.registerNew( reservation ); uow.registerEmail( email, reservation ); // WhatId populated after the insert uow.commitWork(); ``` Emails are sent within the transaction: a failing send rolls back all registered DML. ### IDoWork [#idowork] `IDoWork` is an interface that can be used to implement any database operation which is not supported yet. `registerWork()` registers custom work executed during `commitWork()`, like converting leads, for which no register method exists: the conversion then shares the transaction, savepoint and rollback of the Unit of Work. | Signature | Purpose | | ------------------------------------------------------- | ----------------------------------------------------------- | | `registerWork( dfflib_SObjectUnitOfWork.IDoWork work )` | Execute `work.doWork()` as last operation in `commitWork()` | ```apex public with sharing class LeadConvertWork implements dfflib_SObjectUnitOfWork.IDoWork{ private final List leadConverts = new List(); public void register( Database.LeadConvert leadConvert ){ leadConverts.add( leadConvert ); } public void doWork(){ Database.convertLead( leadConverts ); // one bulkified call for all registered conversions } } // Register the work once, and add the conversions within the loop List leadConverts = new List(); // ... populated by your business logic LeadConvertWork leadConvertWork = new LeadConvertWork(); uow.registerWork( leadConvertWork ); for( Integer i = 0, j = leadConverts.size(); i < j; i++ ){ leadConvertWork.register( leadConverts[ i ] ); } uow.commitWork(); ``` * `doWork()` runs as you define it. Database Context does not apply to it. * An exception thrown in `doWork()` rolls back all registered DML. ### Immediate [#immediate-] Immediate operations call `Database.insertImmediate()`, `updateImmediate()` and `deleteImmediate()`, used for external objects, big objects or special objects (like `ThirdPartyAccountLink`). | Method | `SObject` | `List` | Relationship | | -------------------------- | :---------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------: | :----------: | | `registerNewImmediate` | | | | | `registerDirtyImmediate` | | | | | `registerDeletedImmediate` | | | | ```apex uow.registerNewImmediate( externalRecord ); uow.registerDirtyImmediate( externalRecord ); uow.registerDeletedImmediate( externalRecord ); ``` * Each immediate operation executes before its standard counterpart, see the [commitWork() sequence](#anatomy-how-it-works). * Immediate operations on external objects are not part of the Salesforce transaction: a rollback does not revert them. * DML options and AllOrNone do not apply to immediate operations. ### Priority [#priority-] The fixed sequence of the Unit of Work might sometimes mismatch the business requirement, like when a reservation should be postponed by one day, but updating is not allowed. Then the original reservation should be cancelled before the rescheduled reservation can be inserted, to avoid triggering the overlap validation. Priority operations execute before all standard operations, allowing a deviation from the fixed DML sequence within one Unit of Work. As you can see in the [sequence](#anatomy-how-it-works), priority operations have their own fixed sequence (inserts, updates, upserts, deletes) and are performed sooner, giving a second dimension of control. In fflib, this required multiple Unit of Work instances and commits. | Method | `SObject` | `List` | Relationship | | ------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------: | | `registerPriorityNew` | | | | | `registerPriorityDirty` | | | | | `registerPriorityUpsert` | | | | | `registerPriorityDeleted` | | | | ```apex // Cancel the old booking first (with priority), to free up the room, before inserting the new booking uow.registerPriorityDirty( new RoomReservation__c( Id = oldId, Status__c = DOM_RoomReservations.STATUS_CANCELLED ) ); uow.registerNew( new RoomReservation__c( Room__c = roomId, ... ) ); uow.commitWork(); ``` With `registerDirty`, the insert would execute first and fail on the occupied room. ### SaveResults [#saveresults-] SaveResults are disabled by default, as storing them consumes memory and CPU while they are rarely needed. When partial success should be possible, SaveResults are necessary to determine which records succeeded and which failed. Setting `allOrNone = false` via any [`register*AllOrNone` method](#dml-options-and-allornone-) automatically enables SaveResult storage. When `allOrNone` is disabled via `register*DmlOptions`, call `uow.setSaveResultsRequired( true )` explicitly. ```apex title="CTRL_RoomReservations.createReservations" repo="classes/CTRL_RoomReservations.cls#L59" 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 List saveResults = uow.getNewResults( RoomReservation__c.SObjectType ); Map errors = new Map(); for( Integer i = 0, j = saveResults?.size() ?? 0; i < j; i++ ){ Database.SaveResult sr = saveResults[ i ]; if( !sr.isSuccess() ){ errors.put( i, sr.getErrors()[ 0 ].getMessage() ); } } ``` SaveResult getters are defined to return `null` when no DML ran for that SObjectType or SaveResults were disabled. Hence, null-safe `saveResults?.size() ?? 0`. | Getter | Returns | | ------------------------------------------ | -------------------------------------------------------- | | `getNewResults( SObjectType )` | `List` for inserts | | `getDirtyResults( SObjectType )` | `List` for updates | | `getUpsertResults( SObjectType )` | `List` for upserts by external Id | | `getDeletedResults( SObjectType )` | `List` | | `getUndeletedResults( SObjectType )` | `List` | | `getEmptyRecycleBinResults( SObjectType )` | `List` | | `getPublishResults( SObjectType )` | `List` for published events | | `getEmailResults()` | `List` | | `getApprovalProcessResults()` | `List` | SaveResults are kept after `commitWork()`, and reset automatically at the start of the next `commitWork()`. `uow.resetSaveResults()` clears them manually. Currently, the enablement of SaveResults is for all SObjectTypes. It is on our backlog to narrow this to the specific SObjectType. This would further improve performance for larger transactions. ### Upsert [#upsert] Both fflib and D'fflib have two upsert variants: 1. Simply dispatching to `registerNew()` if the record has no Id, or `registerDirty()` when an Id is set 2. Performing a genuine `Database.upsert()` matching on an external Id field The upsert-specific configurations (`AllOrNone` and SaveResults) apply only to the `externalIdField` variant. | Signature | Behaviour | | ---------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | | `registerUpsert( SObject record )` | Dispatches to `registerNew()` (no `Id`) or `registerDirty()` (`Id` set) | | `registerUpsert( List records )` | Same, bulk | | `registerUpsert( SObject record, SObjectField externalIdField )` | Genuine `Database.upsert()` matching on an external Id field | | `registerUpsert( List records, SObjectField externalIdField )` | Same, bulk | | `registerUpsert( SObject record, SObjectField externalIdField, SObjectField relatedToParentField, SObject relatedToParentRecord )` | Same as single, registering the relationship to the parent inline | For the `Database.upsert()` variant: * The field must be an external Id field, or `Id`, on the same SObjectType as the registered record. * The field should be populated for all registered records. * Multiple external Id fields may be registered for the same SObjectType in one Unit of Work . fflib supports one external Id field per SObjectType. *** ## Testing a Unit of Work [#testing-a-unit-of-work] See [Testing & Mocking](/dfflib/docs/how/testing-mocking) for the full testing patterns. The calling class is tested with a mocked Unit of Work: no DML happens, and you verify what was registered and committed. Examples below come from [`CTRL_RoomReservationsTest`](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/CTRL_RoomReservationsTest.cls) and [`SRVi_RoomReservationsTest`](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/SRVi_RoomReservationsTest.cls). ### Define the mock [#define-the-mock] ```apex fflib_ApexMocks mocks = new fflib_ApexMocks(); dfflib_ISObjectUnitOfWork uowMock = dfflib.unitOfWork.defineMock( mocks ); ``` ### Verify registrations and commit [#verify-registrations-and-commit] ```apex // Standard, simple verifications whether the Unit of Work was called ( ( dfflib_ISObjectUnitOfWork ) mocks.verify( uowMock, 1 ) ).registerNew( reservations ); ( ( dfflib_ISObjectUnitOfWork ) mocks.verify( uowMock, 1 ) ).commitWork(); // Verify the record by its relevant field values, and the relationship to the (new) Contact ( ( dfflib_ISObjectUnitOfWork ) mocks.verify( uowMock, 1 ) ).registerNew( fflib_Match.sObjectWith( new Map{ RoomReservation__c.Room__c => ROOM_ID, RoomReservation__c.CheckInDate__c => CHECK_IN, RoomReservation__c.CheckOutDate__c => CHECK_OUT, RoomReservation__c.Status__c => DOM_RoomReservations.STATUS_SUBMITTED } ), ( Schema.SObjectField ) fflib_Match.eq( RoomReservation__c.Contact__c ), fflib_Match.sObjectWith( expectedContactMap ) ); // Verification can also be done with ArgumentCaptor fflib_ArgumentCaptor argumentCaptor = new fflib_ArgumentCaptor(); ( ( dfflib_ISObjectUnitOfWork ) mocks.verify( uowMock, 1 ) ).registerNew( argumentCaptor.capture() ); List registeredRecords = ( List ) argumentCaptor.getValues(); // ... ``` * Once a matcher is used, every argument needs one: hence `fflib_Match.eq()` for the relationship field. * A mocked `commitWork()` inserts nothing, so registered records keep a `null` Id. Be aware `fflib_Match.anyObject()` does not match `null`, thus use `fflib_Match.isNull()` as backup like in `stubResponseService` of [`SRVi_RoomReservationsTest`](https://github.com/deloitte-engineering/dfflib-code/blob/main/code-examples/main/default/classes/SRVi_RoomReservationsTest.cls#L61). ### Simulate a DML failure [#simulate-a-dml-failure] To simulate a DML failure during commit, use `doThrowWhen`, as `commitWork()` is a void method and cannot return a value. ```apex // Given - set data String exceptionMessage = 'Matching rule fired'; // set mocks mocks.startStubbing(); ( ( dfflib_ISObjectUnitOfWork ) mocks.doThrowWhen( new DmlException( exceptionMessage ), uowMock ) ).commitWork(); mocks.stopStubbing(); ``` ### Stub SaveResults for partial success [#stub-saveresults-for-partial-success] ```apex // The first record succeeds, the second fails List saveResults = new List{ dfflib_UT_Utils.createSaveResult( fflib_IDGenerator.generate( RoomReservation__c.SObjectType ), true, null ), dfflib_UT_Utils.createSaveResult( null, false, dmlMessage ) }; mocks.startStubbing(); mocks.when( uowMock.getNewResults( RoomReservation__c.SObjectType ) ).thenReturn( saveResults ); mocks.stopStubbing(); ``` Mock SaveResults according to the [documentation](https://developer.salesforce.com/docs/platform/apex-ref/references/apex-ref/apex-methods-system-database-saveresult.html).\ The `recordId`, for `saveResult.getId()`, is *only* populated upon successful operations. *** ## Migration steps [#migration-steps] For existing code to leverage D'fflib features, a few migration steps are required. The steps below apply once D'fflib extensions are installed ([Getting Started](/dfflib/docs/how/get-started)). **Caller changes** 1. Ensure `Dfflib_UOW_Config__mdt` records exist with the correct sequence 2. Change `[Application].unitOfWork.newInstance()` to `dfflib.unitOfWork.newInstance()` 3. Pass a Database Context to the Unit of Work to enforce the desired sharing and FLS behaviour **Test class changes** 1. Replace Unit of Work stubs with `dfflib.unitOfWork.defineMock( mocks )`, see [Testing a Unit of Work](#testing-a-unit-of-work) and the [Testing & Mocking](/dfflib/docs/how/testing-mocking) article *** Two constructs have been replaced, since better approaches have been implemented: 1. Custom `IDML` implementations should eventually be replaceable by features like [`Context`](#fflib-set-context) and SaveResults. D'fflib supports running existing `IDML` implementations for backward compatibility. Though this should be used with caution as detailed in "[Running a legacy fflib IDML](#running-a-legacy-fflib-idml)". 2. Overridable `virtual` hooks within the Unit of Work have been removed, as they consumed performance while not adding benefit in the current construct. Carefully review existing `IDML` implementations and hook overrides and migrate their logic to use the new mechanisms provided by D'fflib. If you can't find a fitting migration, [we'd be happy to think along](/dfflib/docs/how/support). D'fflib supports running existing `IDML` implementations, to ease migration and backward compatibility. The internal `LegacyDMLAdapter` converts the `IDML` implementation to make it compatible with D'fflib's Unit of Work. No changes are required to the legacy `IDML` implementations as original `fflib_SObjectUnitOfWork.IDML`, `SimpleDML` etc remain available. To keep using an existing `IDML` while migrating, simply: 1. Call `dfflib.unitOfWork.newInstance( List, IDML )`. 2. Call `dfflib.unitOfWork.newInstance( IDML )` and ensure `Dfflib_UOW_Config__mdt` records exist. References to `SimpleDML` and `UserModeDML` are recommended to be migrated directly. | `IDML` | `Context` | | ------------- | --------- | | `SimpleDML` | `INHERIT` | | `UserModeDML` | `FULL` | IDML Context ```apex fflib_ISObjectUnitOfWork uow = [Application].unitOfWork.newInstance( new fflib_SObjectUnitOfWork.SimpleDML() ); fflib_ISObjectUnitOfWork uow = [Application].unitOfWork.newInstance( new fflib_SObjectUnitOfWork.UserModeDML() ); fflib_ISObjectUnitOfWork uow = [Application].unitOfWork.newInstance( new ProjectSpecificDML() ); ``` ```apex dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( dfflib_Database.Context.INHERIT ); dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( dfflib_Database.Context.FULL ); dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( new ProjectSpecificDML() ); ``` For performance reasons, no safeguards are built in on 'non-IDML-supported methods'. Don't update or extend the Unit of Work, and don't combine a legacy `IDML` with new D'fflib methods. To use new functionality, replace the `IDML` with its D'fflib successor, `dfflib_Database.Context`. * **Works:** `registerNew`, `registerDirty`, `registerUpsert` (the `IDML` must implement `IDMLUpsertable`), `registerDeleted`, `registerPermanentlyDeleted`, the three `registerPublish*` methods, relationships, emails and approval processes. Emails and approvals are sent through the default `INHERIT` proxy, never through the `IDML`. * **Exceptions in `commitWork()`**, rolling back the transaction: priority, immediate and undelete registrations , and `registerUpsert` with an `IDML` that doesn't implement `IDMLUpsertable` (`System.TypeException`). * **Silently ignored:** `register*DmlOptions` and `register*AllOrNone`. `setSaveResultsRequired( true )` returns no SaveResults (they stay `null`). * `setContext()` replaces the legacy `IDML` with the Context proxy. * Call-counts might differ from fflib as D'fflib only calls `IDML` when work is registered. --- # Guidelines URL: /dfflib/docs/how/guidelines/ Elaborating on our guidelines to help smoothen implementation, though project-consistency should always be prioritised. These are recommendations to help achieve maintainable and readable code, but they're not strict rules. What matters most is that agreements are applied consistently within the project and that all developers (including new joiners) can easily understand the structure and reasoning. ## Our aim [#our-aim] In the world of coding there are many different approaches, preferences and perspectives on what constitutes 'proper' and 'readable' code. These are not the definitive guidelines for every situation, but **they will enable projects to realise maintainable code and especially enable future maintainers to succeed**. These guidelines therefore only focus on elements that impact the "hygiene" and "maintainability" of a codebase, refraining from statements about spacing, indentation and other formatting elements, as these are often pre-set by formatters and are largely a matter of preference. This page aims to help developers prioritise maintainability and scalability of their code. The goal is to ensure readability for anyone with coding experience two years from now, which requires consistency, clear naming conventions, meaningful comments, etc. > Treat your code as having two end-users: the user of the functionality and your future self (or another developer). Treat the guidelines below as recommendations, not strict rules. They are 'a way', not 'the way'. What matters most is consistency throughout your project. Agree on one approach, convention and syntax, document it centrally, and commit to it, as a team, now and in the future. ## General guidelines [#general-guidelines] Aim for as little code as needed to get functionality working, while keeping it clear for future maintainers * Prevent duplicate code (DRY) * Make code readable, preferably through proper variable/method/class naming, or else through comments that explain *why* something is done * Remove comments that only state the obvious * Interfaces and abstract classes can be valuable, but only introduce them when they add real value. They often only add complexity and code lines * When one element is referenced multiple times (like `input[0]`), assign it to a local variable Single Responsibility Principle and Separation of Concerns While D'fflib already provides a clear structure, developers should adopt the mindset of giving their logic one clear goal and move other concerns to separate methods. This promotes modularity, reusability, and easier maintenance over time. For example: mock other layers in unit tests to avoid testing layers multiple times and obscuring the focus and clarity of the unit test. All code is always bulkified and reusable * Make it scalable, even if your code doesn't require it yet (such as not doing `input[0]` in Invocable Methods) * Always consider possible reusability or extensions of your code and weigh the impact of preparing now versus future refactoring (without violating SRP or over-engineering) Variables and methods are ordered alphabetically, or else by order of logic * When there is no logical sequence, order all variables and methods alphabetically. This simplifies scanning the code and checking whether e.g. a Domain static already exists. * Domain statics should start with their 'grouping', like `STATUS_OPEN` or `RECTYPE_DEVNAME_CUSTOMER`, so all status or RecordType-related statics are grouped together and easy to scan. * When multiple methods chain together, ordering them in reading sequence helps future readers follow the flow. IDEs help with shortcut navigation to definitions, but sometimes just scrolling through is enough to understand the code. Spend a few minutes now to make your code readable, scalable and bulkified to prevent future hours of confusion; make it a standard to reduce future development time. ## Class naming conventions [#class-naming-conventions] Class names should help readers understand the meaning of a class when looking at it individually, and also provide context about related classes grouped together in the repository, improving overall readability. While not irrefutable we'd prefer: * Use prefixes to group related classes together (e.g. all Services starting with `SRV_`). This groups them in the repository and allows to quickly open another service when new to the project and see how these are implemented. * Use postfixes for test classes to keep them next to the related class. * Avoid ambiguity between SObjects and classes (plural `Accounts` as Domain class vs. singular `Account` as SObject), as this can confuse someone scanning quickly through the code who misreads `Accounts.getName()`. Recommended naming per layer: | Layer/Type | Syntax | | ------------ | ------------------------------------------------------------------------------ | | Domain | `DOM_` | | Entrypoint | `Batch_`, `CTRL_` (for LWC, Aura, VF Controllers), `Flow_`, `Sched_`, `Queue_` | | Service | `SRV_` | | Incoming API | `SRVi_` | | Outgoing API | `SRVo_` | | Test class | `Test` | Projects that have fully adopted sfdx package structures/folders may benefit less from these naming conventions. Powerful IDE search engines also reduce the urgency somewhat. Nevertheless, we consistently see benefits for new joiners and future maintainers when these conventions are in place. ## Optimal collection operations [#optimal-collection-operations] There are many articles documenting the performance differences between for-loops and Map constructions ([like this one](https://www.foxy-solutions.com/salesforce/apex-loop-map-performance-comparisons/)). As a best practice, always default to the most performant collection operation to minimise end-user impact and keep the codebase consistent. Once developers are familiar with the patterns, there is no meaningful difference in readability compared to e.g. for-each loops, while the performance savings can be measured in seconds for end-users. For consistency, even when looping over only 5 records, always use the most efficient approach. **Iterating over an indexed list** ```apex for( Integer i = 0, j = accList.size(); i < j; i++ ){ Account a = accList[ i ]; // do something } // Being up to 75% (!) faster than for-each statements; which should only be used for Set-iterations ``` **Fetching an item from an indexed list** ```apex Account a = accList[ i ]; // Being up to 50% (!) faster than .get( i ); ``` **Skipping `containsKey` when data allows a direct Map.put** ```apex for( Integer i = 0, j = integersList.size(); i < j; i++ ){ m1.put( integersList[ i ], 'ABC' ); } // Being up to 17% faster with no duplicates, and 1% faster with half of keys having a duplicate value (and using containsKey) ``` **Fetch 2nd-level instead of `containsKey` for multi-level Map construction** ```apex Map> accountsByRecTypeDevName = new Map>(); for( Integer i = 0, j = accList.size(); i < j; i++ ){ Account acc = accList[ i ]; List accountsOfRecType = accountsByRecTypeDevName.get( acc.RecordType.DeveloperName ); if( accountsOfRecType == null ){ accountsByRecTypeDevName.put( acc.RecordType.DeveloperName, new List{ acc } ); } else{ accountsOfRecType.add( acc ); } } // Being up to 23% faster than containsKey with 1% existing Keys and 5% for having no duplicate keys ``` ## Test classes [#test-classes] Test classes are one of the hardest classes to keep readable, since everything comes together in one place. They're also often overlooked and underprioritised, despite being a valuable source for understanding complex business logic and ensuring backward compatibility. When done right, multiple or all scenarios should be described, indicating why specific attributes are set. Clear unit test method structure and comments While this can be decided per project, we recommend defining a clear structure for test methods, like: ```apex @IsTest private static void testMethodName(){ // Create mocks // Given - create data // Set mocks // When - perform test // Then - validate ... } ``` Mocking benefits Proper mocking eliminates all code needed to make 'other classes' function and therefore improves maintainability and readability. Yes, it eliminates end-to-end tests, though these formally belong in the (automated) regression test part of the testing pyramid. To avoid mixing concerns, the Trigger Unit Tests can optionally be used as regression tests, so that each test class keeps a single, separate focus. `System.Assert` class Per Winter '23 Salesforce introduced the `System.Assert` class with clearer assertion methods like `Assert.fail()`, `Assert.isNull()`, `Assert.isTrue()` instead of the catch-all `System.assertEquals()`. All unit tests in D'fflib and our projects have shifted to these latest methods to improve readability. Remove default `Test.startTest()` and `Test.stopTest()` Originally `startTest()` was relevant for resetting governor limits after test data creation. With mocking, this has become obsolete and its only remaining relevance is enforcing completion of Async processes before performing asserts. In most unit tests it therefore only consumes time and can be removed. Test classes should be `private with sharing` This enforces the highest security level, purely for consistency, best practices and code scan compliance, since no user context is relevant in test classes when mocking all database interactions. `private` ensures no accidental exposure. ## Frequently asked questions [#frequently-asked-questions] The value D'fflib provides looks different depending on where a developer is in their journey — but it serves both ends of the spectrum. **For junior / reschooled developers** For developers who are self-taught, transitioned from admin roles, or new to software engineering concepts, **explicit structure is more empowering than abstract principles**. A framework says: *"Put this type of logic here."* That is actionable. A principle says: *"Separate your concerns."* That requires interpretation — and for a developer still building their mental model of what "concerns" even means in an Apex context, that interpretation is genuinely hard. D'fflib gives junior developers: * **Reference implementations** — comparable classes from senior developers they can study and absorb * **Factual code reviews** — feedback grounded in shared conventions, not subjective judgement * **A clear growth path** — the framework is strict enough to build good habits, and those habits compound into seniority over time The framework becomes scaffolding. It is not the ceiling — it is the floor that lets them build upward. **For senior / experienced developers** For experienced developers, D'fflib provides something different: **a shared vocabulary for architectural debate**. Senior developers often *want* to challenge where logic lives — whether a method belongs in a Domain or a Service, when a Selector is growing too large, how to split a complex orchestration. D'fflib enables that conversation by giving it structure. The question becomes *"where does this belong within the framework?"* rather than *"what structure should we invent for this?"* D'fflib works for both modes: * Developers with **intrinsic architectural intent** can challenge, debate, and refine — the framework gives them a common language to do so * Developers who **want to ship** get clear, defensible answers without needing to design from first principles every time The framework does not limit experienced developers — it focuses their energy on business problems rather than structural reinvention. --- # Support URL: /dfflib/docs/how/support/ Find the right channel for your current needs. Whether it's a bug, feature request, suggestion, maturity assessment, training or step-by-step support, we're happy to support! ## Channels [#channels] Still have an open question after reading and searching the documentation? Reach out via one of the channels below: | Type | Channel | | --------------------------------- | -------------------------------------------------------------------------------------------- | | Bug or feature request | Raise a [GitHub Issue](https://github.com/deloitte-engineering/dfflib-code/issues) | | Public discussion or question | Start a [GitHub Discussion](https://github.com/deloitte-engineering/dfflib-code/discussions) | | Project specific/private question | Send us an email | ## Adoption challenges [#adoption-challenges] Over time we've often seen companies that installed but only partially adopted the framework. This is typically a combination of insufficient business buy-in, because the narrative focuses on 'technical improvement' or 'technical debt', rather than emphasising the business benefits, and missing the technical knowledge or a clear game plan. We believe this is unfortunate, as the framework is designed to realise faster go-to-markets, reduce development overhead, decrease governor limits, increase developer productivity and even satisfaction. Therefore, we'd like to help tackle your adoption challenges, and realise the ROI of the framework. ### Maturity Assessment [#maturity-assessment] A **data-driven scan of your Salesforce environment** that answers three questions: * **How much** (D')fflib is implemented? *(class counts and coverage per layer)* * **How mature** is the implementation? *(adoption, code quality and best-practice compliance)* * **What's to gain and how?** *(prioritised, impact-ranked recommendations)* This will give you insights in the current status, but more importantly **concrete actionable recommendations** on **how to improve adoption and maturity**, weighing implementation efforts to potential (business) benefits. Enabling you and your development team to take the next steps. Even relevant if you don't have a framework implemented yet, as the scan will draft your full adoption plan and identify your most natural starting points. Allowing you to easily prioritise based on benefits vs. efforts. ### Tailored Trainings [#tailored-trainings] Training sessions to **get your team enabled to leverage the framework**. Going beyond copy-pasting and truly understanding the intent, functioning, impact and benefits. Depending on your preference we can tailor: * Location: Remote or on-site * Duration: Typically ranging from 4 hours to 2 days * Audience: (lead) developers and/or architects * Type: Theoretical vs. hands-on examples * Scope: fflib, D'fflib, general or tailored to your codebase and challenges * Content: (full) introduction, sharpening skills, discussing specific layers or challenges Interested or having a question? Send us an email at . --- # Frequently Asked Questions URL: /dfflib/docs/faq/ This page centralises common questions and answers about D'fflib, grouped per category. ## General [#general] The name is rooted in [fflib-apex-common](https://github.com/apex-enterprise-patterns/fflib-apex-common) — the open-source framework D'fflib builds upon. Keeping `fflib` in the name was intentional: it pays homage to its origins and reflects that D'fflib would not exist without the foundation fflib established, while preserving familiarity and findability for anyone already working with it. The **D'** prefix brings a few meanings together. It carries a quiet nod to Deloitte being the initiating company, and for the mathematically inclined, the apostrophe reads as a prime symbol (′), as in `f′` ("f-prime"), marking D'fflib as the derivative of its origin. Altogether, this allows a clear spoken distinction on "the derived fflib" aka "**the** fflib" in comparison to the original fflib. ## Contributions, bugs and feature requests [#contributions-bugs-and-feature-requests] We welcome all contributions from the community! You can reach out first to align, or directly fork the repository and submit a pull request. Please check the [Contribution Guidelines](https://github.com/deloitte-engineering/dfflib-code/blob/main/CONTRIBUTING.md) for more information. Following them allows us to process contributions swiftly and gives other community members clarity about the context, reasoning and potential impact of each change. If you have an idea for a new feature or improvement but don't have the time or intent to implement it yourself, please share it with the community by submitting a Feature Request in [GitHub Issues](https://github.com/deloitte-engineering/dfflib-code/issues). Please report it in [GitHub Issues](https://github.com/deloitte-engineering/dfflib-code/issues), clearly describing the context, situation, expected outcome and steps to reproduce. If you don't receive a timely response, feel free to reach out directly via one of the channels on our [Support page](/dfflib/docs/how/support#channels). Check our [Support page](/dfflib/docs/how/support#channels) to find the best channel to reach out to us or the community. ## Installation and upgrades [#installation-and-upgrades] There are multiple reasons for D'fflib being provided as unlocked packages: * **Simplified install & upgrade**\ Installs and upgrades complete in minutes via Salesforce link, rather than manual metadata retrieval and saving. * **Reduced project impact**\ Code doesn't need to reside in your repository, keeping it cleaner.\ Unit tests only run during install/upgrade and "all tests", not during regular deployments. * **Full visibility & developer control**\ Code can optionally be retrieved for learning, debugging and encouraging community contribution.\ Or stored in a local folder to enable AI suggestions. * **Flexibility to customise**\ Projects can override package classes to apply project-specific modifications or test new features. Especially since most current `fflib` projects have made customisations, this simplifies the migration to D'fflib.\ Note: overriding is not recommended unless necessary, as it may complicate future upgrades. Unlocked packages do count towards your org's character limits, but the benefits of control and visibility outweigh this. If you have concerns, please reach out so we can discuss and optionally provide a Managed Package. Despite the ambition and intent for modular setups, we've concluded this isn't feasible at the moment. Mostly due to the tight interdependencies between the various components which would make it hard to guarantee stability and compatibility across all components. Though this is definitely a roadmap item. Until then, the repository is already split into folders per feature for readability and maintainability, allowing local customisations to implement only the desired feature. For the easy-install unlocked packages, we provide the default "D'fflib" package (including the latest of `fflib-apex-common` and `fflib-apex-mocks`) and a "D'fflib BYO" (Bring Your Own) extension-package, only shipping D'fflib capabilities. Since the D'fflib full package is defined by the combination of `fflib-apex-common`, `fflib-apex-mocks` and our extensions, it effectively includes all the original fflib classes as well. We've consciously decided to not remove the fflib classes for which we provide extensions (like `fflib_Application`, `fflib_SObjectDomain` and `fflib_SObjectUnitOfWork`) to avoid 'messing' with the core-classes, as developers installing the package might expect the classes. This does imply that auto-completes may show the original fflib classes alongside the D'fflib extensions. In case community feedback suggests that this causes confusion or issues, we may revisit this decision in future versions. No, that is not needed. It is possible to install the full D'fflib package and override the fflib classes via your normal deployment process. This reduces package dependencies and maintenance, while allowing you to apply project-specific customisations. However, when deploying only the delta of changes, be aware that you must re-deploy the overridden classes each time you update the D'fflib package. Share your customisations so we can consider incorporating them into future versions of D'fflib, benefiting the wider community, while simplifying your own project setup. ## Legal & licensing [#legal--licensing] D'fflib is licensed under the same BSD-3-Clause licence as `fflib`, which is a permissive open-source licence that allows you to use, modify, and distribute the software, as long as you comply with the licence terms. The full licence text can be found in the [LICENSE](https://github.com/deloitte-engineering/dfflib-code/blob/main/LICENSE) file. Yes, there are no restrictions on types of projects, nor royalties or fees based on how the software is used — as long as you comply with the three licence conditions. When using D'fflib, you must retain the copyright notice and licence text in your source code. If you redistribute it in binary form (e.g. as part of a packaged product), you must also reproduce the notice in your documentation or distribution materials. You may not use the name of Deloitte or its contributors to promote derived products without written permission. D'fflib is provided "as is", with no warranty or formal support obligation or SLA. The community actively maintains the framework and we do everything in our power to ensure everyone is enabled and no regression issues occur due to the D'fflib framework. That's why the framework is rigorously tested for backward compatibility with previous versions. There is no dependency: you can fully install and apply the framework without any interaction with Deloitte. Usage will always remain free of charge, as will updates, given the community-driven nature of the framework. The only relation to Deloitte is them being the initiators of D'fflib, and offering optional maturity assessments and trainings to help maximise the utilisation and ROI of the framework. ## Project relevancy [#project-relevancy] The layered architecture guides developers to separate concerns and responsibilities, meaning each method or class has a single responsibility. This makes the code easier to understand, test, and modify without affecting other parts of the codebase. A clear example is bulkifying methods (accepting a list of records rather than a single record), which enables future use cases where the same logic needs to run across multiple records without any refactoring. Yes! A well-structured codebase becomes **more valuable** when using AI tools, not less. AI tools like GitHub Copilot, Claude Code, Cursor or similar assistants work significantly better when your code is consistently structured, well-named and following clear conventions. A codebase with D'fflib applied gives AI unambiguous context, as well as a lower risk of one change unintentionally breaking other functionality, due to adherence to [SOLID principles](https://en.wikipedia.org/wiki/SOLID). This leads to lower token usage, less "explain this to me" back-and-forth, and more accurate first-time-right suggestions. Additionally, D'fflib ships with full documentation and a set of ready-to-apply AI skills, directly strengthening AI tool responses for framework-specific patterns. Finally, while AI is here to stay, there is a risk in fully transferring control to AI with no backup plan. If token costs grow, tokens run out, or AI tools are unavailable, a well-structured codebase still allows your team to do the work manually when needed. In short: the framework doesn't only enable humans, it multiplies the value from AI agents as well, while ensuring robust and future-proof delivery. If your project truly has no code, there is no need to install D'fflib. Even with a small codebase, installing D'fflib provides benefits in terms of structure, maintainability, and scalability. It helps ensure that as your project grows, your code remains organised and easy to manage. For larger codebases, D'fflib can be particularly beneficial for improving maintainability and scalability, and can also significantly reduce technical debt and unit test runtimes, improving delivery velocity and reducing costs. Introducing a new framework into an established project can feel daunting, but `fflib` has been adopted at a late project stage many times with significant improvements as the result. D'fflib can be introduced iteratively, starting with small refactorings, to let the team get familiar and gradually adopt. This is fully explained in the [Adoption](/dfflib/docs/how/adoption) guide, and we are here to [support](/dfflib/docs/how/support) you in that journey. ## Others / Contact [#others--contact] Still have an open question after reading this page and searching the docs?\ Check our [Support page](/dfflib/docs/how/support#channels) to find the best channel.