EDP & fflib
Explaining the foundations of our D'fflib framework: Enterprise Design Patterns and fflib.
Highlights & takeaways
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
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)
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)
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 setup for website development, Hexagonal Architecture or usage of UI states (Flux / Redux) 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)
In Martin Fowler's book "Patterns of Enterprise Application Architecture" (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 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). 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 and the current open-source repositories (fflib-apex-common and 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. 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.
How to implement
Curious for some code examples of how to implement the different layers and patterns? Click here.
Benefits of D'fflib on top of fflib
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
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 |
| Selector / Repository | SObject specific class to centralise data retrieval (soql queries) | class SEL_Accounts extends fflib_SObjectSelector → see how to implement |
| Service / Application layer | Orchestrator class for cross-SObject business logic classes | class SRV_OpportunityRenewal → see how to implement |
| Unit of Work | Gathers and executes DML operations centralising transaction management | uow.registerNew( newAccount ); uow.commitWork(); → see how to implement |
| 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 |
For a full overview of the exact layers and their interactions, → check the Layer overview page.