SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

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 FramworksSumitkumar Shingavi
 
Process builder vs Triggers
Process builder vs TriggersProcess builder vs Triggers
Process builder vs TriggersProQuest
 
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 ProblemsSalesforce Developers
 
Salesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexSalesforce DUG - Queueable Apex
Salesforce DUG - Queueable ApexAkshay Varu
 
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 AdoptionWSO2
 
Triggers and order of execution1
Triggers and order of execution1Triggers and order of execution1
Triggers and order of execution1Prabhakar Sharma
 
Your Tests Are Not Your Specs
Your Tests Are Not Your SpecsYour Tests Are Not Your Specs
Your Tests Are Not Your SpecsHillel Wayne
 
Oracle Sql Tuning
Oracle Sql TuningOracle Sql Tuning
Oracle Sql TuningChris Adkin
 
Deployment automation framework with selenium
Deployment automation framework with seleniumDeployment automation framework with selenium
Deployment automation framework with seleniumWenhua Wang
 
Soap UI - Getting started
Soap UI - Getting startedSoap UI - Getting started
Soap UI - Getting startedQualitest
 
Build Your Custom Performance Testing Framework
Build Your Custom Performance Testing FrameworkBuild Your Custom Performance Testing Framework
Build Your Custom Performance Testing FrameworkTechWell
 
Client-Side Performance Testing
Client-Side Performance TestingClient-Side Performance Testing
Client-Side Performance TestingAnand Bagmar
 
Automated testing APEX Applications
Automated testing APEX ApplicationsAutomated testing APEX Applications
Automated testing APEX ApplicationsRoel Hartman
 
Troubleshooting APEX Performance Issues
Troubleshooting APEX Performance IssuesTroubleshooting APEX Performance Issues
Troubleshooting APEX Performance IssuesRoel Hartman
 
Testing lightning components feb 15th 2018
Testing lightning components feb 15th 2018Testing lightning components feb 15th 2018
Testing lightning components feb 15th 2018Richard Clark
 
Agile test-management-test-rail-lastest
Agile test-management-test-rail-lastestAgile test-management-test-rail-lastest
Agile test-management-test-rail-lastestOnur Baskirt
 
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 SiemerAndrew Siemer
 

Was ist angesagt? (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
 

Andere mochten auch

SIBC-OSG Investment Proposal Presentation
SIBC-OSG Investment Proposal PresentationSIBC-OSG Investment Proposal Presentation
SIBC-OSG Investment Proposal PresentationFord Wyatt
 
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 organizationChris Pepin
 
Salesforce Development Best Practices
Salesforce Development Best PracticesSalesforce Development Best Practices
Salesforce Development Best PracticesVivek Chawla
 

Andere mochten auch (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
 

Ähnlich wie Build Triggers Quickly with the Simple Trigger Pattern (STP

Episode 20 - Trigger Frameworks in Salesforce
Episode 20 - Trigger Frameworks in SalesforceEpisode 20 - Trigger Frameworks in Salesforce
Episode 20 - Trigger Frameworks in SalesforceJitendra Zaa
 
Apex code Benchmarking
Apex code BenchmarkingApex code Benchmarking
Apex code BenchmarkingAmit Chaudhary
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tipsBill Buchan
 
Validation for APIs in Laravel 4
Validation for APIs in Laravel 4Validation for APIs in Laravel 4
Validation for APIs in Laravel 4Kirk Bushell
 
Plc Programming Fundamentals
Plc Programming FundamentalsPlc Programming Fundamentals
Plc Programming FundamentalsLiving Online
 
Automated testing with Cypress
Automated testing with CypressAutomated testing with Cypress
Automated testing with CypressYong Shean Chong
 
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)Vivek Chawla
 
Saleforce For Domino Dogs
Saleforce For Domino DogsSaleforce For Domino Dogs
Saleforce For Domino DogsMark Myers
 
Owasp tds
Owasp tdsOwasp tds
Owasp tdssnyff
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
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 implementDefconRussia
 
Lotuscript for large systems
Lotuscript for large systemsLotuscript for large systems
Lotuscript for large systemsBill Buchan
 
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 UseSalesforce Developers
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
The Evolution of Development Testing
The Evolution of Development TestingThe Evolution of Development Testing
The Evolution of Development TestingCathal King
 
GCP Deployment- Vertex AI
GCP Deployment- Vertex AIGCP Deployment- Vertex AI
GCP Deployment- Vertex AITriloki Gupta
 
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
 

Ähnlich wie Build Triggers Quickly with the Simple Trigger Pattern (STP (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...
 

Mehr von Vivek Chawla

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...Vivek Chawla
 
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 ISVsVivek Chawla
 
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)Vivek Chawla
 
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)Vivek Chawla
 
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)Vivek Chawla
 
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 OverviewVivek Chawla
 

Mehr von 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
 

Kürzlich hochgeladen

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
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 GoalsJhone kinadey
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
+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
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
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.pdfkalichargn70th171
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
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 🔝✔️✔️Delhi Call girls
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
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.docxComplianceQuest1
 
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...ICS
 

Kürzlich hochgeladen (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
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
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
+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...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
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
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
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
 
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 🔝✔️✔️
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
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
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
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...
 

Build Triggers Quickly with the Simple Trigger Pattern (STP

  • 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

Hinweis der Redaktion

  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