- SalesforceChaCha
- Posts
- ๐ Taming your DML chaos ๐บ
๐ Taming your DML chaos ๐บ
Peeping the Unit of Work pattern in Apex
Good morning, Salesforce Nerds! Have you ever found yourself drowning in a sea of DML operations? ๐
If so, youโve likely encountered the classic challenge of transactional consistency (or the lack thereof) in Apex. ๐ฐ
It can be a slog, but donโt stress! We got you!
Today, weโre going to break down the Unit of Work (UoW) pattern - your new best friend in managing bulkified, efficient, and rollback-safe database operations on the Salesforce platform! ๐ฅ
Letโs get it! ๐ช

TABLE OF CONTENTS
Taming your DML chaos
BECAUSE SCATTERED DML SHOULD BE A CRIME
WHAT IS THE UNIT OF WORK PATTERN?
The Unit of Work pattern is a design pattern that helps manage transactional consistency by batching database operations together, deferring execution until the end of a process. ๐คฏ
What the heck does that mean for use Salesforce developers?
Well, in Apex, this means:
๐ฆ๏ธ Packaging DML operations together (to minimize unnecessary database hits)
๐ Maintaining a list of records that need inserting, updating, or deleting in memory
๐ฅ Committing all changes at once to avoid partial failures
โฉ๏ธ Enabling rollback in case of an error (kind of like a mini transaction manager)
Itโs like preparing all your ingredients for a recipe before actually cooking - ensuring nothing gets left out and any clean-up is a breeze!
THE SECRET INGREDIENTS TO DML MASTERY
KEY COMPONENTS
Instead of executing DML operations immediately, records are staged and processed together at the end of a transaction, improving efficiency and ensuring data consistency. ๐
This approach not only minimizes database hits but also helps prevent partial failures by enforcing an all-or-nothing execution model.
Letโs look at the key components in more detail ๐๏ธ
๐ Registering Records
Instead of executing insert, update, or delete immediately, you register records with the Unit of Work object.
โณ๏ธ Deferring DML Execution
No DML is performed immediately - remember, everything is staged until you commit your work.
๐ฅ Commit Everything at Once
At the end of execution, all staged DML operations run in bulk via DML operations or Database Class Methods.
๐๏ธ Rollback Support
If an error occurs, the entire transaction fails gracefully instead of leaving data in a half-updated state.
BUZZWORDS YOUโLL PRETEND YOU ALWAYS KNEW
IMPORTANT TERMINOLOGY
Like any pattern you need to learn some of the lingo - which Iโm sure youโre picking up on by now. ๐ฃ๏ธ
Transaction โ A single unit of execution where all operations must succeed or fail together.
Committing Changes โ Persisting all database changes in one go.
Rollback โ Undoing changes when something goes wrong.
Bulkification โ Ensuring operations are optimized for large datasets.
FROM CHAOS TO CONTROL
HOW TO IMPLEMENT
Letโs see this Unit of Work in action with a simplified Apex implementation! (Read: donโt implement this - itโs purposely watered down so the masses can grasp the concept!)
๐ฅ Step 1: Create a UnitOfWork Class
Isnโt is beautiful?!? ๐คฉ
public class UnitOfWork {
private List<SObject> recsToInsert = new List<SObject>();
private List<SObject> recsToUpdate = new List<SObject>();
private List<SObject> recsToDelete = new List<SObject>();
public void registerInsert(SObject record) {
recsToInsert.add(record);
}
public void registerUpdate(SObject record) {
recsToUpdate.add(record);
}
public void registerDelete(SObject record) {
recsToDelete.add(record);
}
public void commitWork() {
// You're definitely gonna want some exception handling here
if (!recsToInsert.isEmpty()) insert recordsToInsert;
if (!recsToUpdate.isEmpty()) update recordsToUpdate;
if (!recsToDelete.isEmpty()) delete recordsToDelete;
}
}
๐ฅ Step 2: Use the Unit of Work in Your Client Code
// The chacha is tightly coupling!?! ๐ฑ๐ฑ๐ฑ
UnitOfWork uow = new UnitOfWork();
// Registering records for batch processing
Account acc = new Account(Name = 'New Customer');
Contact con = new Contact(LastName = 'Doe');
// Register both of these as new - note you will need a way to also register relationships. This is built into Apex Enterprise Patterns!
uow.registerInsert(acc);
uow.registerInsert(con);
// Updating records
acc.Industry = 'Technology';
uow.registerUpdate(acc);
// Deleting records
uow.registerDelete(con);
// Committing all changes at once
uow.commitWork();๐ Boom! Thatโs it.
Instead of scattered DML statements, weโve batched them, reducing database hits and improving efficiency.
Dang โฆ weโre good. ๐
GO FORTH AND UOW LIKE A PRO
FINAL THOUGHTS
The Unit of Work pattern is a game-changer for transactional consistency and bulk processing in Apex. ๐ฏ
Donโt sleep on it.
Whether you're cleaning up messy DML or ensuring data integrity, this pattern helps you write cleaner, more efficient code. ๐ฅ
Not to mention it keeps Salesforce governors happy!
And who doesnโt want that?
Happy coding! ๐งโ๐ป
SOUL FOOD
Todayโs Principle
"Where there is data smoke, there is business fire."
and now....Salesforce Memes



What did you think about today's newsletter? |