- 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? |