SlideShare une entreprise Scribd logo
1  sur  20
Build Great Triggers Quickly with
STP (the Simple Trigger Pattern)
Vivek M. Chawla
Salesforce MVP | Senior Software Developer – Intuit
@VivekMChawla
Vivek M. Chawla
Salesforce MVP | Senior Software Engineer, Intuit | @VivekMChawla
Review Three Key Trigger Best Practices
Introduce the Simple Trigger Pattern (STP)
Demo
Q & A
Overview
Best Practices for Apex Triggers
Trigger logic is usually…
• Complex
• Often mission critical!
• Entwined with other logic
• You don’t always control the other logic!
• High Volume
• Build for scale now…Don’t play catch-up later!
Why is This Important?
trigger AccountValidation on Account
(before insert, before update) {
// Do validation stuff...
}
trigger AccountRollup on Account
(after insert, after update) {
// Do rollup stuff...
}
trigger ShadowAccountBuilder on Account
(after insert, after update) {
// Do contact building stuff...
}
Why is this important?
• Multiple triggers don’t have a guaranteed order of
execution
• Code in multiple triggers leads to duplicated logic
• Duplicated logic is harder to maintain
Best Practice #1
“One Trigger Per Object”
trigger AccountTrigger on Account
(before insert, before update,
after insert, after update) {
if (Trigger.isBefore && Trigger.isInsert) {
// Do validation stuff...
}
else if (Trigger.isBefore && Trigger.isUpdate) {
// Do validation stuff...
}
else if (Trigger.isAfter && Trigger.isInsert) {
// Do rollup stuff...
// Do shadow account stuff...
}
else if (Trigger.isAfter && Trigger.isUpdate) {
// Do rollup stuff...
// Do shadow account stuff...
}
}
Recommendations
• Define a single “master” trigger
• Capture all “trigger actions” in the master trigger
• Use trigger context variables to determine what
trigger action is being executed
Best Practice #1
“One Trigger Per Object”
trigger AccountTrigger on Account
(before insert, before update,
after insert, after update) {
if (Trigger.isBefore && Trigger.isInsert) {
// Do validation stuff...
}
else if (Trigger.isBefore && Trigger.isUpdate) {
// Do validation stuff...
}
else if (Trigger.isAfter && Trigger.isInsert) {
// Do rollup stuff...
// Do shadow account stuff...
}
else if (Trigger.isAfter && Trigger.isUpdate) {
// Do rollup stuff...
// Do shadow account stuff...
}
}
Why is this important?
• Trigger code isn’t “full featured” Apex
• No access to static variables
• Logic in triggers is not reusable
Best Practice #2
“No Business Logic in Triggers”
trigger AccountTrigger on Account
(before insert, before update,
after insert, after update) {
AccountTriggerHandler
handler = new AccountTriggerHandler();
if (Trigger.isBefore && Trigger.isInsert) {
handler.beforeInsert();
}
else if (Trigger.isBefore && Trigger.isUpdate) {
handler.beforeUpdate();
}
else if (Trigger.isAfter && Trigger.isInsert) {
handler.afterInsert();
}
else if (Trigger.isAfter && Trigger.isUpdate) {
handler.afterUpdate();
}
}
Recommendations
• Implement a Trigger Handler Class
• Dispatch to specific “Action Handler” methods
• Leverage Service Classes for greater reusability
Best Practice #2
“No Business Logic in Triggers”
public class AccountTriggerHandler {
public void
afterInsert(list<Account> newAccounts,
map<Id, Account> newAccountsMap) {
// Create shadow accounts
list<Account> shadowAccs = new list<Account>();
for (Account newAccount : newAccounts) {
Account shadowAcc = new Account();
shadowAcc.Name = newAccount.Name
+ ‘ (Shadow)’;
shadowAccs.add(shadowAccount);
}
insert shadowAccs;
}
}
Why is this important?
• Sometimes trigger logic may execute more than
once in a single transaction
• Not good if you don’t want this to happen!
• Things that can cause recursion include
• Workflow fires that causes a field update
• Trigger performs DML on a same-type object
Best Practice #3
“Prevent Recursion Using Static Variables”
public class AccountTriggerHandler {
// Define a recursion check variable.
private static boolean aiFirstRun = true;
public void
afterInsert(list<Account> newAccounts,
map<Id, Account> newAccountsMap) {
// Check the “first run” flag.
if (aiFirstRun == false) {
return;
}
// Flip the “first run” flag.
aiFirstRun = false;
// Create shadow accounts...
createShadowAccounts(newAccounts);
}
}
Recommendations
• Use static variables to create a “gatekeeper” for your
trigger logic
• Solves recursion issues in large majority of use
cases
• Bonus Tip: Use private helper methods to keep
handler methods semantically clean and direct
Best Practice #3
“Prevent Recursion Using Static Variables”
Bulkified Code is not a trigger best practice...
Bulkified Code is an Apex best practice!
• Bulkification means your code can handle batches
of 200 records
• Service and Utility methods should be “bulkified from
birth”
• An Apex developer should always think “bulk first”
Wait a Minute…What About Bulkification?
The Simple Trigger Pattern (STP)
Many Excellent Alternatives
• Tidy Pattern
• Simple Trigger Template
• TriggerX
• Hari Krishnan’s Framework
• Andrew Fawcett’s SOC
• Just to name a few...
Wait…Do we Really Need Another Trigger Pattern?
Simple
Trigger
Pattern
• One parent class
• One test class
• One Apex trigger template
• One Apex class template
• Encapsulates multiple best
practices
• Enables rapid development
• Provides a straightforward
standard that’s easy to implement
GitHub Repository
• bit.ly/SimpleTriggerPattern
GitHub Gist
• bit.ly/SimpleTriggerPatternGist
What Is It? What Does It Offer? Where Can I Get It?
Introducing the Simple Trigger Pattern (STP)
Demo
Three critical best practices for writing Apex triggers
• “One trigger per object”
• “No business logic in triggers”
• “Prevent recursion using static variables”
Introduced the Simple Trigger Pattern
Learned where to get and how to use the code
Review
GitHub Repo
• bit.ly/SimpleTriggerPattern
GitHub Gist
• bit.ly/SimpleTriggerPatternGist
Tidy Pattern
• bit.ly/TidyTriggerPattern
Simple Trigger Template
• bit.ly/SimpleTriggerTemplate
TriggerX
• bit.ly/TriggerXPattern
Hari Krishnan’s Pattern
• bit.ly/HariKrishnansPattern
GistBox
• GistBoxApp.com
Trigger Frameworks and Apex
Trigger Best Practices
• sforce.co/1IMaN3n
Andrew Fawcett on “Separation
of Concerns”
• bit.ly/FawcettBlogSOC
Simple Trigger Pattern (STP) Other Trigger Patterns Tools & Helpful Articles
Resources
Q&A
@VivekMChawla
Thank you

Contenu connexe

Tendances

WSO2 Test Automation Framework : Approach and Adoption
WSO2 Test Automation Framework : Approach and AdoptionWSO2 Test Automation Framework : Approach and Adoption
WSO2 Test Automation Framework : Approach and Adoption
WSO2
 

Tendances (20)

Salesforce Meetup 18 April 2015 - Apex Trigger & Scheduler Framworks
Salesforce Meetup 18 April 2015 - Apex Trigger & Scheduler FramworksSalesforce Meetup 18 April 2015 - Apex Trigger & Scheduler Framworks
Salesforce Meetup 18 April 2015 - Apex Trigger & Scheduler Framworks
 
Process builder vs Triggers
Process builder vs TriggersProcess builder vs Triggers
Process builder vs Triggers
 
Apex Trigger Debugging: Solving the Hard Problems
Apex Trigger Debugging: Solving the Hard ProblemsApex Trigger Debugging: Solving the Hard Problems
Apex Trigger Debugging: Solving the Hard Problems
 
Salesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexSalesforce DUG - Queueable Apex
Salesforce DUG - Queueable Apex
 
05 managing transactions
05   managing transactions05   managing transactions
05 managing transactions
 
Apex code (Salesforce)
Apex code (Salesforce)Apex code (Salesforce)
Apex code (Salesforce)
 
WSO2 Test Automation Framework : Approach and Adoption
WSO2 Test Automation Framework : Approach and AdoptionWSO2 Test Automation Framework : Approach and Adoption
WSO2 Test Automation Framework : Approach and Adoption
 
Triggers and order of execution1
Triggers and order of execution1Triggers and order of execution1
Triggers and order of execution1
 
Your Tests Are Not Your Specs
Your Tests Are Not Your SpecsYour Tests Are Not Your Specs
Your Tests Are Not Your Specs
 
Oracle Sql Tuning
Oracle Sql TuningOracle Sql Tuning
Oracle Sql Tuning
 
Deployment automation framework with selenium
Deployment automation framework with seleniumDeployment automation framework with selenium
Deployment automation framework with selenium
 
Grails Services
Grails ServicesGrails Services
Grails Services
 
Soap UI - Getting started
Soap UI - Getting startedSoap UI - Getting started
Soap UI - Getting started
 
Build Your Custom Performance Testing Framework
Build Your Custom Performance Testing FrameworkBuild Your Custom Performance Testing Framework
Build Your Custom Performance Testing Framework
 
Client-Side Performance Testing
Client-Side Performance TestingClient-Side Performance Testing
Client-Side Performance Testing
 
Automated testing APEX Applications
Automated testing APEX ApplicationsAutomated testing APEX Applications
Automated testing APEX Applications
 
Troubleshooting APEX Performance Issues
Troubleshooting APEX Performance IssuesTroubleshooting APEX Performance Issues
Troubleshooting APEX Performance Issues
 
Testing lightning components feb 15th 2018
Testing lightning components feb 15th 2018Testing lightning components feb 15th 2018
Testing lightning components feb 15th 2018
 
Agile test-management-test-rail-lastest
Agile test-management-test-rail-lastestAgile test-management-test-rail-lastest
Agile test-management-test-rail-lastest
 
Load testing with Visual Studio and Azure - Andrew Siemer
Load testing with Visual Studio and Azure - Andrew SiemerLoad testing with Visual Studio and Azure - Andrew Siemer
Load testing with Visual Studio and Azure - Andrew Siemer
 

En vedette (6)

Bulkify Your Org
Bulkify Your OrgBulkify Your Org
Bulkify Your Org
 
HyperBatch
HyperBatchHyperBatch
HyperBatch
 
SIBC-OSG Investment Proposal Presentation
SIBC-OSG Investment Proposal PresentationSIBC-OSG Investment Proposal Presentation
SIBC-OSG Investment Proposal Presentation
 
The impact of mobile on the IT organization
The impact of mobile on the IT organizationThe impact of mobile on the IT organization
The impact of mobile on the IT organization
 
Salesforce Development Best Practices
Salesforce Development Best PracticesSalesforce Development Best Practices
Salesforce Development Best Practices
 
Best Practices for Testing in salesforce.com
Best Practices for Testing in salesforce.comBest Practices for Testing in salesforce.com
Best Practices for Testing in salesforce.com
 

Similaire à Build Great Triggers Quickly with STP (the Simple Trigger Pattern)

Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tips
Bill Buchan
 
Plc Programming Fundamentals
Plc Programming FundamentalsPlc Programming Fundamentals
Plc Programming Fundamentals
Living Online
 
Lotuscript for large systems
Lotuscript for large systemsLotuscript for large systems
Lotuscript for large systems
Bill Buchan
 
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
Codecamp Romania
 

Similaire à Build Great Triggers Quickly with STP (the Simple Trigger Pattern) (20)

Episode 20 - Trigger Frameworks in Salesforce
Episode 20 - Trigger Frameworks in SalesforceEpisode 20 - Trigger Frameworks in Salesforce
Episode 20 - Trigger Frameworks in Salesforce
 
Apex code Benchmarking
Apex code BenchmarkingApex code Benchmarking
Apex code Benchmarking
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tips
 
Validation for APIs in Laravel 4
Validation for APIs in Laravel 4Validation for APIs in Laravel 4
Validation for APIs in Laravel 4
 
Plc Programming Fundamentals
Plc Programming FundamentalsPlc Programming Fundamentals
Plc Programming Fundamentals
 
Production-ready Software
Production-ready SoftwareProduction-ready Software
Production-ready Software
 
Automated testing with Cypress
Automated testing with CypressAutomated testing with Cypress
Automated testing with Cypress
 
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
 
Saleforce For Domino Dogs
Saleforce For Domino DogsSaleforce For Domino Dogs
Saleforce For Domino Dogs
 
Owasp tds
Owasp tdsOwasp tds
Owasp tds
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Alexey Sintsov- SDLC - try me to implement
Alexey Sintsov- SDLC - try me to implementAlexey Sintsov- SDLC - try me to implement
Alexey Sintsov- SDLC - try me to implement
 
Lotuscript for large systems
Lotuscript for large systemsLotuscript for large systems
Lotuscript for large systems
 
Five Enterprise Development Best Practices That EVERY Salesforce Org Can Use
Five Enterprise Development Best Practices That EVERY Salesforce Org Can UseFive Enterprise Development Best Practices That EVERY Salesforce Org Can Use
Five Enterprise Development Best Practices That EVERY Salesforce Org Can Use
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
The Evolution of Development Testing
The Evolution of Development TestingThe Evolution of Development Testing
The Evolution of Development Testing
 
GCP Deployment- Vertex AI
GCP Deployment- Vertex AIGCP Deployment- Vertex AI
GCP Deployment- Vertex AI
 
In (database) automation we trust
In (database) automation we trustIn (database) automation we trust
In (database) automation we trust
 
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
Iasi code camp 20 april 2013 marian chicu - database unit tests in the sql se...
 

Plus de Vivek Chawla

Plus de Vivek Chawla (6)

Dreamforce 2019 Five Reasons Why CLI Plugins are a Salesforce Partners Secret...
Dreamforce 2019 Five Reasons Why CLI Plugins are a Salesforce Partners Secret...Dreamforce 2019 Five Reasons Why CLI Plugins are a Salesforce Partners Secret...
Dreamforce 2019 Five Reasons Why CLI Plugins are a Salesforce Partners Secret...
 
Salesforce DX 201 - Advanced Implementation for ISVs
Salesforce DX 201 - Advanced Implementation for ISVsSalesforce DX 201 - Advanced Implementation for ISVs
Salesforce DX 201 - Advanced Implementation for ISVs
 
Salesforce DX Update for ISVs (October 2017)
Salesforce DX Update for ISVs (October 2017)Salesforce DX Update for ISVs (October 2017)
Salesforce DX Update for ISVs (October 2017)
 
Start a Developer Group and take TrailheaDX Home With You! (TDX'17)
Start a Developer Group and take TrailheaDX Home With You! (TDX'17)Start a Developer Group and take TrailheaDX Home With You! (TDX'17)
Start a Developer Group and take TrailheaDX Home With You! (TDX'17)
 
Squash Bugs with the Apex Debugger (TDX'17)
Squash Bugs with the Apex Debugger (TDX'17)Squash Bugs with the Apex Debugger (TDX'17)
Squash Bugs with the Apex Debugger (TDX'17)
 
San Diego Salesforce User Group - Lightning Overview
San Diego Salesforce User Group - Lightning OverviewSan Diego Salesforce User Group - Lightning Overview
San Diego Salesforce User Group - Lightning Overview
 

Dernier

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 

Dernier (20)

Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 

Build Great Triggers Quickly with STP (the Simple Trigger Pattern)

  • 1. Build Great Triggers Quickly with STP (the Simple Trigger Pattern) Vivek M. Chawla Salesforce MVP | Senior Software Developer – Intuit @VivekMChawla
  • 2. Vivek M. Chawla Salesforce MVP | Senior Software Engineer, Intuit | @VivekMChawla
  • 3. Review Three Key Trigger Best Practices Introduce the Simple Trigger Pattern (STP) Demo Q & A Overview
  • 4. Best Practices for Apex Triggers
  • 5. Trigger logic is usually… • Complex • Often mission critical! • Entwined with other logic • You don’t always control the other logic! • High Volume • Build for scale now…Don’t play catch-up later! Why is This Important?
  • 6. trigger AccountValidation on Account (before insert, before update) { // Do validation stuff... } trigger AccountRollup on Account (after insert, after update) { // Do rollup stuff... } trigger ShadowAccountBuilder on Account (after insert, after update) { // Do contact building stuff... } Why is this important? • Multiple triggers don’t have a guaranteed order of execution • Code in multiple triggers leads to duplicated logic • Duplicated logic is harder to maintain Best Practice #1 “One Trigger Per Object”
  • 7. trigger AccountTrigger on Account (before insert, before update, after insert, after update) { if (Trigger.isBefore && Trigger.isInsert) { // Do validation stuff... } else if (Trigger.isBefore && Trigger.isUpdate) { // Do validation stuff... } else if (Trigger.isAfter && Trigger.isInsert) { // Do rollup stuff... // Do shadow account stuff... } else if (Trigger.isAfter && Trigger.isUpdate) { // Do rollup stuff... // Do shadow account stuff... } } Recommendations • Define a single “master” trigger • Capture all “trigger actions” in the master trigger • Use trigger context variables to determine what trigger action is being executed Best Practice #1 “One Trigger Per Object”
  • 8. trigger AccountTrigger on Account (before insert, before update, after insert, after update) { if (Trigger.isBefore && Trigger.isInsert) { // Do validation stuff... } else if (Trigger.isBefore && Trigger.isUpdate) { // Do validation stuff... } else if (Trigger.isAfter && Trigger.isInsert) { // Do rollup stuff... // Do shadow account stuff... } else if (Trigger.isAfter && Trigger.isUpdate) { // Do rollup stuff... // Do shadow account stuff... } } Why is this important? • Trigger code isn’t “full featured” Apex • No access to static variables • Logic in triggers is not reusable Best Practice #2 “No Business Logic in Triggers”
  • 9. trigger AccountTrigger on Account (before insert, before update, after insert, after update) { AccountTriggerHandler handler = new AccountTriggerHandler(); if (Trigger.isBefore && Trigger.isInsert) { handler.beforeInsert(); } else if (Trigger.isBefore && Trigger.isUpdate) { handler.beforeUpdate(); } else if (Trigger.isAfter && Trigger.isInsert) { handler.afterInsert(); } else if (Trigger.isAfter && Trigger.isUpdate) { handler.afterUpdate(); } } Recommendations • Implement a Trigger Handler Class • Dispatch to specific “Action Handler” methods • Leverage Service Classes for greater reusability Best Practice #2 “No Business Logic in Triggers”
  • 10. public class AccountTriggerHandler { public void afterInsert(list<Account> newAccounts, map<Id, Account> newAccountsMap) { // Create shadow accounts list<Account> shadowAccs = new list<Account>(); for (Account newAccount : newAccounts) { Account shadowAcc = new Account(); shadowAcc.Name = newAccount.Name + ‘ (Shadow)’; shadowAccs.add(shadowAccount); } insert shadowAccs; } } Why is this important? • Sometimes trigger logic may execute more than once in a single transaction • Not good if you don’t want this to happen! • Things that can cause recursion include • Workflow fires that causes a field update • Trigger performs DML on a same-type object Best Practice #3 “Prevent Recursion Using Static Variables”
  • 11. public class AccountTriggerHandler { // Define a recursion check variable. private static boolean aiFirstRun = true; public void afterInsert(list<Account> newAccounts, map<Id, Account> newAccountsMap) { // Check the “first run” flag. if (aiFirstRun == false) { return; } // Flip the “first run” flag. aiFirstRun = false; // Create shadow accounts... createShadowAccounts(newAccounts); } } Recommendations • Use static variables to create a “gatekeeper” for your trigger logic • Solves recursion issues in large majority of use cases • Bonus Tip: Use private helper methods to keep handler methods semantically clean and direct Best Practice #3 “Prevent Recursion Using Static Variables”
  • 12. Bulkified Code is not a trigger best practice... Bulkified Code is an Apex best practice! • Bulkification means your code can handle batches of 200 records • Service and Utility methods should be “bulkified from birth” • An Apex developer should always think “bulk first” Wait a Minute…What About Bulkification?
  • 13. The Simple Trigger Pattern (STP)
  • 14. Many Excellent Alternatives • Tidy Pattern • Simple Trigger Template • TriggerX • Hari Krishnan’s Framework • Andrew Fawcett’s SOC • Just to name a few... Wait…Do we Really Need Another Trigger Pattern? Simple Trigger Pattern
  • 15. • One parent class • One test class • One Apex trigger template • One Apex class template • Encapsulates multiple best practices • Enables rapid development • Provides a straightforward standard that’s easy to implement GitHub Repository • bit.ly/SimpleTriggerPattern GitHub Gist • bit.ly/SimpleTriggerPatternGist What Is It? What Does It Offer? Where Can I Get It? Introducing the Simple Trigger Pattern (STP)
  • 16. Demo
  • 17. Three critical best practices for writing Apex triggers • “One trigger per object” • “No business logic in triggers” • “Prevent recursion using static variables” Introduced the Simple Trigger Pattern Learned where to get and how to use the code Review
  • 18. GitHub Repo • bit.ly/SimpleTriggerPattern GitHub Gist • bit.ly/SimpleTriggerPatternGist Tidy Pattern • bit.ly/TidyTriggerPattern Simple Trigger Template • bit.ly/SimpleTriggerTemplate TriggerX • bit.ly/TriggerXPattern Hari Krishnan’s Pattern • bit.ly/HariKrishnansPattern GistBox • GistBoxApp.com Trigger Frameworks and Apex Trigger Best Practices • sforce.co/1IMaN3n Andrew Fawcett on “Separation of Concerns” • bit.ly/FawcettBlogSOC Simple Trigger Pattern (STP) Other Trigger Patterns Tools & Helpful Articles Resources

Notes de l'éditeur

  1. Trigger logic is “high volume” Called often Processes records in “bulk” Trigger logic is mission critical Direct result of business needs Trigger logic has to play nice with everybody Workflows Processes Other triggers