SlideShare a Scribd company logo
1 of 25
Apex 10 Commandments
James Loghry
Technical Architect, EDL Consulting
@dancinllama
Kevin Poorman
Principle Architect, EDL Consulting
@CodeFriar
James Loghry
Technical Architect
Kevin Poorman
Principle Architect
Commandments 1-5
Kevin Poorman
#1 Thou Shalt keep thy code Stupid Simple. (Kiss)
#1 Thou shalt keep thy code Stupid Simple. (Kiss)
#2 Thou shalt not put queries in for loops
#2 Thou shalt not put queries in for loops
#3 Thou shalt not put DML in for loops
#3 Thou shalt not put DML in for loops
Why bulkification?
Salesforce runs on a multi-
tenant architecture. Hence,
governor limits and bulkification
are needed.
#4 Thou shalt only put one trigger per object
#5 Thou shalt not put code in triggers other than calling
methods and managing execution order
Commandments 6-10
James Loghry
#6 Thou shalt have a happy balance
between clicks & code
– “I’ve reached the maximum number of workflows”
– Triggers that replicate declarative functionality.
• Roll-up summary
• Workflows
• Flow Triggers
– Using Custom Settings instead of constructing a map in
Apex
– Using formulas instead of duplicating fields
Know which tool
is right for the
job.
#7 Thou shalt utilize maps for queries when needed
#8 Thou shalt make use of relationships to reduce
queries wherever possible
#9 Thou shalt aim for 100% test coverage
In general test your methods for:
 Positive effects.
• Given proper input it should act like this.
• Not just happy path, but all logic branches.
 Negative effects.
• Given bad data it should error like this.
 Role/Profile/User effects
 Given a user with X profile and Y role it should act like this.
 Bulkification
• Load 200 or more records to test limits.
#10 Thou shalt write meaningful and useful tests
• Not a test without System.assert calls
• System.assert(A==B,’A does not equal B’)
• System.AssertEquals(A,B)
• System.AssertNotEquals(A,B,’A equals B, but shouldnt’)
• The more assertions the better.
• Create mock data, never rely on existing production data.
• Test all conditions, not just positive test cases
• Test one criteria per unit test.
#Bonus! Thou shalt feel free to break these as
wisdom merits.
After all:
 Sometimes you just need a list of Id’s
 These commandments, despite their
name, are guidelines for success, not
syntactical rules you just can’t break.
 Break them if you need to, Adhere if you
can – they’ll save you time in the long run.
Except for
bulkfiying SOQL
and DML!
Questions & Answers
10 Apex Commandments for Simple, Tested Code

More Related Content

What's hot

The Art of Gherkin Scripting - Matt Eakin
The Art of Gherkin Scripting - Matt EakinThe Art of Gherkin Scripting - Matt Eakin
The Art of Gherkin Scripting - Matt EakinQA or the Highway
 
Developer Night - Opticon18
Developer Night - Opticon18Developer Night - Opticon18
Developer Night - Opticon18Optimizely
 
Automate Debugging with git bisect
Automate Debugging with git bisectAutomate Debugging with git bisect
Automate Debugging with git bisectCamille Bell
 
Episode 13 - Advanced Apex Triggers
Episode 13 - Advanced Apex TriggersEpisode 13 - Advanced Apex Triggers
Episode 13 - Advanced Apex TriggersJitendra Zaa
 
A/B Testing at Scale: Minimizing UI Complexity (SXSW 2015)
A/B Testing at Scale: Minimizing UI Complexity (SXSW 2015)A/B Testing at Scale: Minimizing UI Complexity (SXSW 2015)
A/B Testing at Scale: Minimizing UI Complexity (SXSW 2015)Chris Saint-Amant
 
Apex Flex Queue: Batch Apex Liberated
Apex Flex Queue: Batch Apex LiberatedApex Flex Queue: Batch Apex Liberated
Apex Flex Queue: Batch Apex LiberatedCarolEnLaNube
 
Growing Manual Testers into Automators
Growing Manual Testers into AutomatorsGrowing Manual Testers into Automators
Growing Manual Testers into AutomatorsCamille Bell
 
Building Test Automations the agile way
Building Test Automations the agile way Building Test Automations the agile way
Building Test Automations the agile way MakeMyTrip.com
 
Enabling CD in Enterprises with Testing
Enabling CD in Enterprises with TestingEnabling CD in Enterprises with Testing
Enabling CD in Enterprises with TestingThoughtworks
 
Episode 20 - Trigger Frameworks in Salesforce
Episode 20 - Trigger Frameworks in SalesforceEpisode 20 - Trigger Frameworks in Salesforce
Episode 20 - Trigger Frameworks in SalesforceJitendra Zaa
 
Client-Side Performance Testing
Client-Side Performance TestingClient-Side Performance Testing
Client-Side Performance TestingAnand Bagmar
 
Easy Automated UI Testing with Canopy
Easy Automated UI Testing with CanopyEasy Automated UI Testing with Canopy
Easy Automated UI Testing with CanopyEric Potter
 
Sustainable Automation Frameworks by Kelsey Shannahan
Sustainable Automation Frameworks by Kelsey ShannahanSustainable Automation Frameworks by Kelsey Shannahan
Sustainable Automation Frameworks by Kelsey ShannahanQA or the Highway
 

What's hot (13)

The Art of Gherkin Scripting - Matt Eakin
The Art of Gherkin Scripting - Matt EakinThe Art of Gherkin Scripting - Matt Eakin
The Art of Gherkin Scripting - Matt Eakin
 
Developer Night - Opticon18
Developer Night - Opticon18Developer Night - Opticon18
Developer Night - Opticon18
 
Automate Debugging with git bisect
Automate Debugging with git bisectAutomate Debugging with git bisect
Automate Debugging with git bisect
 
Episode 13 - Advanced Apex Triggers
Episode 13 - Advanced Apex TriggersEpisode 13 - Advanced Apex Triggers
Episode 13 - Advanced Apex Triggers
 
A/B Testing at Scale: Minimizing UI Complexity (SXSW 2015)
A/B Testing at Scale: Minimizing UI Complexity (SXSW 2015)A/B Testing at Scale: Minimizing UI Complexity (SXSW 2015)
A/B Testing at Scale: Minimizing UI Complexity (SXSW 2015)
 
Apex Flex Queue: Batch Apex Liberated
Apex Flex Queue: Batch Apex LiberatedApex Flex Queue: Batch Apex Liberated
Apex Flex Queue: Batch Apex Liberated
 
Growing Manual Testers into Automators
Growing Manual Testers into AutomatorsGrowing Manual Testers into Automators
Growing Manual Testers into Automators
 
Building Test Automations the agile way
Building Test Automations the agile way Building Test Automations the agile way
Building Test Automations the agile way
 
Enabling CD in Enterprises with Testing
Enabling CD in Enterprises with TestingEnabling CD in Enterprises with Testing
Enabling CD in Enterprises with Testing
 
Episode 20 - Trigger Frameworks in Salesforce
Episode 20 - Trigger Frameworks in SalesforceEpisode 20 - Trigger Frameworks in Salesforce
Episode 20 - Trigger Frameworks in Salesforce
 
Client-Side Performance Testing
Client-Side Performance TestingClient-Side Performance Testing
Client-Side Performance Testing
 
Easy Automated UI Testing with Canopy
Easy Automated UI Testing with CanopyEasy Automated UI Testing with Canopy
Easy Automated UI Testing with Canopy
 
Sustainable Automation Frameworks by Kelsey Shannahan
Sustainable Automation Frameworks by Kelsey ShannahanSustainable Automation Frameworks by Kelsey Shannahan
Sustainable Automation Frameworks by Kelsey Shannahan
 

Viewers also liked

How to Make a Career as an Admin by Denise Carbone
How to Make a Career as an Admin by Denise CarboneHow to Make a Career as an Admin by Denise Carbone
How to Make a Career as an Admin by Denise CarboneSalesforce Admins
 
Salesforce developer conference tokyo2013
Salesforce developer conference tokyo2013Salesforce developer conference tokyo2013
Salesforce developer conference tokyo2013Ikou Sanuki
 
Choose your Destiny - Building your Awesome Admin Career - Video Link: http:/...
Choose your Destiny - Building your Awesome Admin Career - Video Link: http:/...Choose your Destiny - Building your Awesome Admin Career - Video Link: http:/...
Choose your Destiny - Building your Awesome Admin Career - Video Link: http:/...Deepa Patel
 
Formula Ninja at Dreamforce 2014
Formula Ninja at Dreamforce 2014Formula Ninja at Dreamforce 2014
Formula Ninja at Dreamforce 2014Deepa Patel
 
Expert Hour - Salesforce Integration Tools
Expert Hour - Salesforce Integration ToolsExpert Hour - Salesforce Integration Tools
Expert Hour - Salesforce Integration ToolsGeraldine Gray
 
My TopCoder Journey - How I reinvented myself as a Developer
My TopCoder Journey - How I reinvented myself as a DeveloperMy TopCoder Journey - How I reinvented myself as a Developer
My TopCoder Journey - How I reinvented myself as a DeveloperGaurav Kheterpal
 
Tree Traversal #SalesforceSaturday
Tree Traversal #SalesforceSaturdayTree Traversal #SalesforceSaturday
Tree Traversal #SalesforceSaturdayDaniel Peter
 

Viewers also liked (7)

How to Make a Career as an Admin by Denise Carbone
How to Make a Career as an Admin by Denise CarboneHow to Make a Career as an Admin by Denise Carbone
How to Make a Career as an Admin by Denise Carbone
 
Salesforce developer conference tokyo2013
Salesforce developer conference tokyo2013Salesforce developer conference tokyo2013
Salesforce developer conference tokyo2013
 
Choose your Destiny - Building your Awesome Admin Career - Video Link: http:/...
Choose your Destiny - Building your Awesome Admin Career - Video Link: http:/...Choose your Destiny - Building your Awesome Admin Career - Video Link: http:/...
Choose your Destiny - Building your Awesome Admin Career - Video Link: http:/...
 
Formula Ninja at Dreamforce 2014
Formula Ninja at Dreamforce 2014Formula Ninja at Dreamforce 2014
Formula Ninja at Dreamforce 2014
 
Expert Hour - Salesforce Integration Tools
Expert Hour - Salesforce Integration ToolsExpert Hour - Salesforce Integration Tools
Expert Hour - Salesforce Integration Tools
 
My TopCoder Journey - How I reinvented myself as a Developer
My TopCoder Journey - How I reinvented myself as a DeveloperMy TopCoder Journey - How I reinvented myself as a Developer
My TopCoder Journey - How I reinvented myself as a Developer
 
Tree Traversal #SalesforceSaturday
Tree Traversal #SalesforceSaturdayTree Traversal #SalesforceSaturday
Tree Traversal #SalesforceSaturday
 

Similar to 10 Apex Commandments for Simple, Tested Code

Salesforce Apex Ten Commandments
Salesforce Apex Ten CommandmentsSalesforce Apex Ten Commandments
Salesforce Apex Ten CommandmentsNetStronghold
 
Driving application development through behavior driven development
Driving application development through behavior driven developmentDriving application development through behavior driven development
Driving application development through behavior driven developmentEinar Ingebrigtsen
 
4 TSPN_Apex 10 Commandments
4 TSPN_Apex 10 Commandments4 TSPN_Apex 10 Commandments
4 TSPN_Apex 10 CommandmentsTerraSky
 
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...FalafelSoftware
 
An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1Blue Elephant Consulting
 
代码大全(内训)
代码大全(内训)代码大全(内训)
代码大全(内训)Horky Chen
 
Test Driven Development with Laravel
Test Driven Development with LaravelTest Driven Development with Laravel
Test Driven Development with LaravelTyler Johnston
 
The View - Lotusscript coding best practices
The View - Lotusscript coding best practicesThe View - Lotusscript coding best practices
The View - Lotusscript coding best practicesBill Buchan
 
Finding a good development partner
Finding a good development partnerFinding a good development partner
Finding a good development partnerKevin Poorman
 
An Introduction to unit testing
An Introduction to unit testingAn Introduction to unit testing
An Introduction to unit testingSteven Casey
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tipsBill Buchan
 
{10.0} Test Driven Development.pptx
{10.0} Test Driven Development.pptx{10.0} Test Driven Development.pptx
{10.0} Test Driven Development.pptxAmalEldhose2
 
Unit testing
Unit testingUnit testing
Unit testingPiXeL16
 
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...AgileNetwork
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven DevelopmentPablo Villar
 

Similar to 10 Apex Commandments for Simple, Tested Code (20)

The Apex Ten Commandments
The Apex Ten CommandmentsThe Apex Ten Commandments
The Apex Ten Commandments
 
Salesforce Apex Ten Commandments
Salesforce Apex Ten CommandmentsSalesforce Apex Ten Commandments
Salesforce Apex Ten Commandments
 
Driving application development through behavior driven development
Driving application development through behavior driven developmentDriving application development through behavior driven development
Driving application development through behavior driven development
 
4 TSPN_Apex 10 Commandments
4 TSPN_Apex 10 Commandments4 TSPN_Apex 10 Commandments
4 TSPN_Apex 10 Commandments
 
QA and scrum
QA and scrumQA and scrum
QA and scrum
 
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...
 
An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1
 
代码大全(内训)
代码大全(内训)代码大全(内训)
代码大全(内训)
 
Test Driven Development with Laravel
Test Driven Development with LaravelTest Driven Development with Laravel
Test Driven Development with Laravel
 
The View - Lotusscript coding best practices
The View - Lotusscript coding best practicesThe View - Lotusscript coding best practices
The View - Lotusscript coding best practices
 
Finding a good development partner
Finding a good development partnerFinding a good development partner
Finding a good development partner
 
An Introduction to unit testing
An Introduction to unit testingAn Introduction to unit testing
An Introduction to unit testing
 
Tdd
TddTdd
Tdd
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tips
 
{10.0} Test Driven Development.pptx
{10.0} Test Driven Development.pptx{10.0} Test Driven Development.pptx
{10.0} Test Driven Development.pptx
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Unit testing
Unit testingUnit testing
Unit testing
 
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
 
Clean code
Clean codeClean code
Clean code
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven Development
 

Recently uploaded

Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
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
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 

Recently uploaded (20)

Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
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
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 

10 Apex Commandments for Simple, Tested Code

  • 1. Apex 10 Commandments James Loghry Technical Architect, EDL Consulting @dancinllama Kevin Poorman Principle Architect, EDL Consulting @CodeFriar
  • 5. #1 Thou Shalt keep thy code Stupid Simple. (Kiss)
  • 6. #1 Thou shalt keep thy code Stupid Simple. (Kiss)
  • 7. #2 Thou shalt not put queries in for loops
  • 8. #2 Thou shalt not put queries in for loops
  • 9. #3 Thou shalt not put DML in for loops
  • 10. #3 Thou shalt not put DML in for loops
  • 11. Why bulkification? Salesforce runs on a multi- tenant architecture. Hence, governor limits and bulkification are needed.
  • 12. #4 Thou shalt only put one trigger per object
  • 13. #5 Thou shalt not put code in triggers other than calling methods and managing execution order
  • 15. #6 Thou shalt have a happy balance between clicks & code – “I’ve reached the maximum number of workflows” – Triggers that replicate declarative functionality. • Roll-up summary • Workflows • Flow Triggers – Using Custom Settings instead of constructing a map in Apex – Using formulas instead of duplicating fields Know which tool is right for the job.
  • 16. #7 Thou shalt utilize maps for queries when needed
  • 17. #8 Thou shalt make use of relationships to reduce queries wherever possible
  • 18. #9 Thou shalt aim for 100% test coverage In general test your methods for:  Positive effects. • Given proper input it should act like this. • Not just happy path, but all logic branches.  Negative effects. • Given bad data it should error like this.  Role/Profile/User effects  Given a user with X profile and Y role it should act like this.  Bulkification • Load 200 or more records to test limits.
  • 19. #10 Thou shalt write meaningful and useful tests • Not a test without System.assert calls • System.assert(A==B,’A does not equal B’) • System.AssertEquals(A,B) • System.AssertNotEquals(A,B,’A equals B, but shouldnt’) • The more assertions the better. • Create mock data, never rely on existing production data. • Test all conditions, not just positive test cases • Test one criteria per unit test.
  • 20.
  • 21.
  • 22.
  • 23. #Bonus! Thou shalt feel free to break these as wisdom merits. After all:  Sometimes you just need a list of Id’s  These commandments, despite their name, are guidelines for success, not syntactical rules you just can’t break.  Break them if you need to, Adhere if you can – they’ll save you time in the long run. Except for bulkfiying SOQL and DML!

Editor's Notes

  1. DEMO: Showing developer console Executing code and showing error List<Account> accLst = new List<Account>([SELECT Id, Name FROM Account LIMIT 100]); for (Account acc : accLst){ Integer numWithEmail = 0; List<Contact> contactLst = new List<Contact>([SELECT Id, Email FROM Contact WHERE AccountId = :acc.Id]); for (Contact cont : contactLst){ if (Cont.Email != null){ numWithEmail++; } } System.debug(acc.Name+' has '+numWithEmail+' contacts with emails'); } Make sure log levels are: DB: Info Callouts : Error Apex Code: Debug Validation: Error Workflow: Error Profilng: Debug Visualforce: Error System: Error
  2. DEMO: Change code in developer console. Show debug log with now a query limit of 1. List<Account> accLst = new List<Account>([SELECT Id, Name, (SELECT Id, Email FROM Contacts) FROM Account LIMIT 100]); for (Account acc : accLst){ Integer numWithEmail = 0; for (Contact cont : acc.Contacts){ if (Cont.Email != null){ numWithEmail++; } } System.debug(acc.Name+' has '+numWithEmail+' contacts with emails'); }
  3. DEMO: Showing developer console Executing code and showing error List<Account> accLst = new List<Account>([SELECT Id, Name FROM Account LIMIT 100]); for (Account acc : accLst){ Integer numWithEmail = 0; List<Contact> contactLst = new List<Contact>([SELECT Id, Email FROM Contact WHERE AccountId = :acc.Id]); for (Contact cont : contactLst){ if (Cont.Email != null){ numWithEmail++; } } System.debug(acc.Name+' has '+numWithEmail+' contacts with emails'); } Make sure log levels are: DB: Info Callouts : Error Apex Code: Debug Validation: Error Workflow: Error Profilng: Debug Visualforce: Error System: Error
  4. DEMO: Change code in developer console. Show debug log with now a query limit of 1. List<Account> accLst = new List<Account>([SELECT Id, Name, (SELECT Id, Email FROM Contacts) FROM Account LIMIT 100]); for (Account acc : accLst){ Integer numWithEmail = 0; for (Contact cont : acc.Contacts){ if (Cont.Email != null){ numWithEmail++; } } System.debug(acc.Name+' has '+numWithEmail+' contacts with emails'); }
  5. DEMO: Showing developer console Executing code and showing error List<Account> accLst = new List<Account>([SELECT Id, Name, Contacts_with_Email_Address__c, (SELECT Id, Email FROM Contacts) FROM Account LIMIT 151]); for (Account acc : accLst){ Integer numWithEmail = 0; for (Contact cont : acc.Contacts){ if (Cont.Email != null){ numWithEmail++; } } System.debug(acc.Name+' has '+numWithEmail+' contacts with emails'); acc.Contacts_with_Email_Address__c = numWithEmail; update acc; }
  6. List<Account> accLst = new List<Account>([SELECT Id, Name, Contacts_with_Email_Address__c, (SELECT Id, Email FROM Contacts) FROM Account LIMIT 151]); List<Account> accToUpd = new List<Account>(); for (Account acc : accLst){ Integer numWithEmail = 0; for (Contact cont : acc.Contacts){ if (Cont.Email != null){ numWithEmail++; } } System.debug(acc.Name+' has '+numWithEmail+' contacts with emails'); if (acc.Contacts_with_Email_Address__c <> numWithEmail){ acc.Contacts_with_Email_Address__c = numWithEmail; accToUpd.add(acc); } } update accToUpd;
  7. List<Account> accLst = new List<Account>([SELECT Id, Name, Contacts_with_Email_Address__c, (SELECT Id, Email FROM Contacts) FROM Account LIMIT 151]); List<Account> accToUpd = new List<Account>(); for (Account acc : accLst){ Integer numWithEmail = 0; for (Contact cont : acc.Contacts){ if (Cont.Email != null){ numWithEmail++; } } System.debug(acc.Name+' has '+numWithEmail+' contacts with emails'); if (acc.Contacts_with_Email_Address__c <> numWithEmail){ acc.Contacts_with_Email_Address__c = numWithEmail; accToUpd.add(acc); } } update accToUpd;
  8. Declarative crazy. 500+ fields on an object, loads of workflows – It can get really hard to see what’s going on in the same way bad coding can be hard.
  9. When querying for a collection of records, you can query into either a list or a map. By default it seems we all learn to query into a list, like we see there in the first block of code. In complex logic situations the ability to pull from the collection a specific record, by it’s id is essential. In refactoring situations it’s easy to convert your list to a map (line 10)
  10. Queries are limited. Use your queries wisely, and remember to query UP. Start with the childmost object and reference parent objects through the relationship __r fields
  11. Positive Test cases should check for expected results not only of the unit overall but of logic branches.
  12. Positive Test Case Mock Data Setup
  13. Exception test scenario
  14. Negative test scenario