SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado

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
 

Destacado (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
 

Similar a 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
 

Similar a 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...
 

Más de 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
 

Más 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
 

Último

Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 

Último (20)

Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 

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

Notas del editor

  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