Guidelines
Elaborating on our guidelines to help smoothen implementation, though project-consistency should always be prioritised.
Highlights & takeaways
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
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
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_OPENorRECTYPE_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 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
Accountsas Domain class vs. singularAccountas SObject), as this can confuse someone scanning quickly through the code who misreadsAccounts.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 |
Packaging
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
There are many articles documenting the performance differences between for-loops and Map constructions (like this one). 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
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-iterationsFetching an item from an indexed list
Account a = accList[ i ];
// Being up to 50% (!) faster than .get( i );Skipping containsKey when data allows a direct Map.put
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
Map<String, List<Account>> accountsByRecTypeDevName = new Map<String, List<Account>>();
for( Integer i = 0, j = accList.size(); i < j; i++ ){
Account acc = accList[ i ];
List<Account> accountsOfRecType = accountsByRecTypeDevName.get( acc.RecordType.DeveloperName );
if( accountsOfRecType == null ){
accountsByRecTypeDevName.put( acc.RecordType.DeveloperName, new List<Account>{ acc } );
} else{
accountsOfRecType.add( acc );
}
}
// Being up to 23% faster than containsKey with 1% existing Keys and 5% for having no duplicate keysTest 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:
@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
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.
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.
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!