SlideShare a Scribd company logo
Building Strong Foundations Apex
Enterprise Patterns
Andrew Fawcett
FinancialForce.com, CTO
@andyinthecloud
About
GREAT ALONE. BETTER TOGETHER.
‱ Native to Salesforce1ℱ Platform
since 2009
‱ Investors include Salesforce Ventures
‱ 650+ employees, San Francisco based
2
Session Resources
Follow the Session in the Dreamforce App, I will
share this slide deck and other related links on the
Feed
Be social and feel free to ask follow up questions!

What's wrong with this picture?
What's wrong with this picture?
Developer “A”
writes an Apex
Controller first
Developer “B”
writes an Apex
Batch job later.
So what was wrong with that picture?
Developer “A”
Developer “B”
MyControllerMyController Issue
Use of ApexPages.currentPage() Unnecessary and fragile, utilize instead
stdController.getId() method
Error handling No try/catch error handling on controller
method
MyBatchJob Issue
Use of ApexPages.currentPage() Is not available in a Batch Apex context, the constructor
code will give an exception.
SOQL Query and DML Governors Calling the controller method in a loop will cause a SOQL
query and DML governor issues.
Error Handling No try/catch error handling in the the execute method
Separation of Concerns Developer A did not originally develop the controller logic
expecting or anticipating Developer B’s would in the future
try to reuse it from a Batch Context as well.
They did not consider correct Separation of Concerns

selectById
selectByXXX
queryLocatorById
SOQL
new DomainClass(
.) processRecords(
)
Domain Class Service Class
Selector Class
QueryLocator start(
)
execute(
)
Finish(
)
Batch Apex
Service Boundary
query
queryquery
Pattern Checklist
Separation of Concerns ☐
Service Layer ☐
Domain Layer ☐
Selector Layer ☐
So what is “Separation of Concerns” then?
“The goal is to design systems so that
functions can be optimized
independently of other functions, so
that failure of one function does not
cause other functions to fail, and in
general to make it easier to
understand, design and manage
complex interdependent systems”
Wikipedia, “Separation of Concerns”
Base Reference Material, Inspiration and Further Reading
Service Layer
Domain Layer
‱ Yet another Wrapper / Trigger pattern!
Selector Layer
Reference Martin Fowler
‱ http://martinfowler.com/eaaCatalog/
‱ Author of “Patterns of Enterprise
Application Architecture”
Salesforce Wiki Reference
‱ http://wiki.developerforce.com/page/Apex_Enterprise_Patterns_-_Separation_of_Concerns
Apex Enterprise Patterns Sample Application
GitHub: financialforcedev/fflib-apex-common-samplecode
Apex Enterprise Patterns Architecture
selectById
selectByXXX
queryLocatorById
SOQL
new DomainClass(
.) processRecords(
)
Domain Class Service Class
Selector Class
QueryLocator start(
)
execute(
)
Finish(
)
Batch Apex
Service Boundary
query
queryquery
NOTE: You may also find Controllers consuming your Selector classes at times.
Brief introduction to the Factory pattern

‱ In class-based programming, the factory
method pattern is a creational pattern
which uses factory methods to deal with
the problem of creating objects without
specifying the exact class of object that
will be created.
http://en.wikipedia.org/wiki/Factory_metho
d_pattern
With and without an Application Factory

Without With
- Just use new operator whenever
- Simpler code base, no Apex Interfaces
- No mocking support
- No polymorphic domain
- Adhoc Unit of Work configuration
- Use Application class instead of new operator
- Must use Apex Interfaces to define SOC
- ApexMocks support
- Ability to leverage Polymorphic Domains
- Standardized Unit of Work throughout
When creating instances of Service, Domain, Selector and Unit of Work classes

Want to know more about Application factory?
Just a regular class named Application with some public static final members in it!
Further Reading
.
Unit Testing, Apex Enterprise Patterns and ApexMocks – Part 1
Unit Testing, Apex Enterprise Patterns and ApexMocks – Part 2
selectById
selectByXXX
queryLocatorById
SOQL
new DomainClass(
.) processRecords(
)
Domain Class Service Class
Selector Class
QueryLocator start(
)
execute(
)
Finish(
)
Batch Apex
Service Boundary
query
queryquery
Pattern Checklist
Separation of Concerns 
Service Layer ☐
Domain Layer ☐
Selector Layer ☐
Introducing the Service Layer
Introducing the Service Layer : Naming and Methods
Naming Convention
 Suffix with ‘Service’, e.g. OpportunitiesService
 Methods named by purpose not usage, e.g. applyDiscounts
 Stateless, uses with sharing and global optional for API readyness
Introducing the Service Layer : Caller Benefits
Clear Code Factoring
 Encapsulates Processes / Tasks
 Caller Context Agnostic, Controller class calling it example

Introducing the Service Layer : Example Method
Defined Responsibilities
 Supports Bulkifcation
 Transaction management
Developing and calling a Service Layer
Service Contract
Developer
“A” follows
Service
Layer
pattern.
Developer “A”
writes
Controller
code to
consume the
Service.
Developer
“B” then
reuses the
Developer
“A” code
safely.
AccountService.cls
MyController.cls
MyBatch.cls
Code Walkthrough : Sample Services
Managing DML and Transactions
‱ Unit of Work Pattern
Classes
OpportunitiesServiceImpl.cls
Code Walkthrough : Custom Buttons
Custom Buttons
‱ Detail and List View
‱ Calling Visualforce Controller Code
Visualforce Controllers and Pages
‱ Error Handling
‱ Interacts with Service Layer
‱ Utilize bulkified methods
‱ Assume transaction containment
‱ Catch exceptions and display them on the page
Classes and Pages
OpportunityApplyDiscountController.cls
‱ opportunityapplydiscount.page
‱ opportunityapplydiscounts.page
OpportunityCreateInvoiceController.cls
‱ opportunitycreateinvoice.page
‱ opportunitycreateinvoices.page
Code Walkthrough : Batch Apex
Classes
CreatesInvoicesJob.cls
 Error Handling
 Interacts with Service Layer
‱ Utilize bulkified methods, Assume transaction containment
‱ Catch exceptions and logs them for later notification
selectById
selectByXXX
queryLocatorById
SOQL
new DomainClass(
.) processRecords(
)
Domain Class Service Class
Selector Class
QueryLocator start(
)
execute(
)
Finish(
)
Batch Apex
Service Boundary
query
queryquery
Pattern Checklist
Separation of Concerns 
Service Layer 
Domain Layer ☐
Selector Layer ☐
Introducing the Domain Layer
Domain Class
Service
Layer
Visualforce
Controller
Apex
Webservice
Inbound
Email
Handler
Batch Apex
Scheduled
Apex
JavaScript
Remo ng
Apex Rest
Service Class
Domain Class
Domain Class
Domain Class
Domain
Layer
Database Manipula on
via Apex Trigger
Service Opera ons
via Apex Calls
Custom
Objects
Standard UI
Layouts
Formulas Reports
Dashboards
Workflow
Custom Object Custom Object
Bulkifica on of DML
Unit of Work
Service Class
Custom Object Service Class
Introducing the Domain Layer
Naming Convention
 Name uses plural name of object, e.g. Opportunities
NOTE: This class implements an interface and the newInstance method, required
only if using Application factory
Introducing the Domain Layer
Clear Code Factoring
 Encapsulates Validation
/ Defaulting of Fields
 Wraps Apex Trigger Logic
in Apex Class
(Trigger/Wrapper Pattern)
Introducing the Domain Layer
Defined Responsibilities
 Enforces Bulkifcation for logic
 Platform security best practice
(honors Users profile)
 Encapsulates ALL logic / behavior
for each object
‱ e.g. onValidate, onBeforeInsert and applyDiscount
Introducing the Domain Layer : Apex Trigger Flow
Code Walkthrough : Domain Layer : Apex Triggers
What no code?!?  Triggers
OpportunitiesTrigger.trigger
OpportunityLineItemsTrigger.trigger
selectById
selectByXXX
queryLocatorById
SOQL
new DomainClass(
.) processRecords(
)
Domain Class Service Class
Selector Class
QueryLocator start(
)
execute(
)
Finish(
)
Batch Apex
Service Boundary
query
queryquery
Pattern Checklist
Separation of Concerns 
Service Layer 
Domain Layer 
Selector Layer ☐
Introducing the Selector Layer
selectById
selectByXXX
queryLocatorById
SOQL
new DomainClass(
.) processRecords(
)
Domain Class Service Class
Selector Class
QueryLocator start(
)
execute(
)
Finish(
)
Batch Apex
Service Boundary
query
queryquery
NOTE: You may also find Controllers consuming your Selector classes at times.
Introducing the Selector Layer
Naming Convention
 Plural object name suffixed by Selector
‱ e.g. OpportunitiesSelector
NOTE: Interface and newInstance method not
required if your not using the Application factory
Introducing the Selector Layer
Clear Code Factoring
 Encapsulates Query Logic
Introducing the Selector Layer
Defined Responsibilities
 Consistency over queried fields
 Platform security best practice
‱ Configurable
 Encapsulates ALL query logic
Code Walkthrough : Selector Layer : Callers
Service Layer Logic : OpportunitiesSelector.selectByIdWithProducts
Domain Layer Logic : AccountsSelector.selectByOpportunity
Apex Class
OpportunitiesServiceImpl.cls
Apex Class
Opportunities.cls
NOTE: Above example leverages feature of Selector factory
selectById
selectByXXX
queryLocatorById
SOQL
new DomainClass(
.) processRecords(
)
Domain Class Service Class
Selector Class
QueryLocator start(
)
execute(
)
Finish(
)
Batch Apex
Service Boundary
query
queryquery
Pattern Checklist
Separation of Concerns 
Service Layer 
Domain Layer 
Selector Layer 
Summary
Summary
When is SOC / DRY appropriate (a rough guide)?
Solution / Code
Base Size
Developers Requirements Scope Number of Client Types
and Interactions
SOC/DRY
Appropriate?
Small 1 to 2 ‱ Well known and unlikely to
change
‱ One off solutions
‱ Limited number of objects
‱ Standard UI
‱ Simple VF / Triggers
‱ No Batch Mode
‱ No API
‱ No Mobile
Typically not
Small to Medium 1 to 6 ‱ Well known but may need to
evolve rapidly
‱ Growing number objects and
processes interacting
‱ Product deliverable or larger
duration projects
‱ Standard UI
‱ Advanced VF / JQuery
‱ Batch Mode
‱ API (on roadmap)
‱ Mobile (on roadmap)
Worth
considering
Large > 6 ‱ Scope driven by multiple
customers and user types
‱ Large number of objects
‱ Generic product or solution
aimed at Mid to Enterprise
market with Customer or
Partner Integrations.
‱ Growing development team!
‱ Standard UI
‱ Advanced VF / JQuery
‱ Batch Mode
‱ Developer / Partner API
‱ Mobile Clients
‱ New Platform Feature
Ready, Chatter Actions!
Definite benifits
Session Resources
Follow the Session in the Dreamforce App, I will
share this slide deck and other related links on the
Feed
Be social and feel free to ask follow up questions!

Building strong foundations apex enterprise patterns
3
Earn a GoPro prize entry for each completed
survey
Tap the bell to take a survey2Enroll in a session1
Share Your Feedback, and Win a GoPro!

More Related Content

PDF
Scrum 101: Introduction to Scrum
PPTX
Introduction to apex code
PPTX
Diabetes Mellitus
PPTX
Hypertension
PPTX
Republic Act No. 11313 Safe Spaces Act (Bawal Bastos Law).pptx
PPTX
Power Point Presentation on Artificial Intelligence
PDF
Caça palavras - Bullying
Scrum 101: Introduction to Scrum
Introduction to apex code
Diabetes Mellitus
Hypertension
Republic Act No. 11313 Safe Spaces Act (Bawal Bastos Law).pptx
Power Point Presentation on Artificial Intelligence
Caça palavras - Bullying

What's hot (20)

PDF
Apex Enterprise Patterns: Building Strong Foundations
PDF
Apex Design Patterns
PDF
Apex Design Patterns
PPTX
Introduction to Apex for Developers
PPT
Salesforce Integration
PDF
Best Practices with Apex in 2022.pdf
PDF
Introduction to Apex Triggers
PPT
Salesforce Presentation
PDF
Lightning web components episode 2- work with salesforce data
PPTX
Salesforce Cross-Cloud Architecture
PPTX
Salesforce Flows Architecture Best Practices
PDF
Lwc presentation
PPTX
Seamless Authentication with Force.com Canvas
PPTX
Salesforce Integration Patterns
PPTX
Introduction to lightning Web Component
PDF
Salesforce Application Lifecycle Management presented to EA Forum by Sam Garf...
PDF
Forecasting Accurately with Salesforce Forecasting
PPTX
Episode 10 - External Services in Salesforce
PPTX
salesforce-101-overview-training.pptx
PDF
Making External Web Pages Interact With Visualforce
Apex Enterprise Patterns: Building Strong Foundations
Apex Design Patterns
Apex Design Patterns
Introduction to Apex for Developers
Salesforce Integration
Best Practices with Apex in 2022.pdf
Introduction to Apex Triggers
Salesforce Presentation
Lightning web components episode 2- work with salesforce data
Salesforce Cross-Cloud Architecture
Salesforce Flows Architecture Best Practices
Lwc presentation
Seamless Authentication with Force.com Canvas
Salesforce Integration Patterns
Introduction to lightning Web Component
Salesforce Application Lifecycle Management presented to EA Forum by Sam Garf...
Forecasting Accurately with Salesforce Forecasting
Episode 10 - External Services in Salesforce
salesforce-101-overview-training.pptx
Making External Web Pages Interact With Visualforce
Ad

Viewers also liked (17)

PPTX
Salesforce World Tour 2016 : Lightning Out : Components on any Platform
PPTX
Introduction to Analytics Cloud
PDF
Real-time SQL Access to Your Salesforce.com Data Using Progress Data Direct
PDF
Apex Connector for Lightning Connect: Make Anything a Salesforce Object
PPTX
Lightning strikes twice- SEDreamin
PPTX
Force.com Canvas in the Publisher and Chatter Feed
PPTX
Go Faster with Process Builder
PDF
Lightning Connect: Lessons Learned
PDF
Lightning Out: Components for the Rest of the World
PDF
Lightning Connect Custom Adapters: Connecting Anything with Salesforce
PDF
Two-Way Integration with Writable External Objects
PDF
Design Patterns for Asynchronous Apex
PPTX
Apex collection patterns
PDF
Secure Salesforce: Lightning Components Best Practices
PPTX
Access External Data in Real-time with Lightning Connect
PPTX
Internet of things the salesforce lego machine cloud
PPTX
Enterprise Architecture Salesforce
Salesforce World Tour 2016 : Lightning Out : Components on any Platform
Introduction to Analytics Cloud
Real-time SQL Access to Your Salesforce.com Data Using Progress Data Direct
Apex Connector for Lightning Connect: Make Anything a Salesforce Object
Lightning strikes twice- SEDreamin
Force.com Canvas in the Publisher and Chatter Feed
Go Faster with Process Builder
Lightning Connect: Lessons Learned
Lightning Out: Components for the Rest of the World
Lightning Connect Custom Adapters: Connecting Anything with Salesforce
Two-Way Integration with Writable External Objects
Design Patterns for Asynchronous Apex
Apex collection patterns
Secure Salesforce: Lightning Components Best Practices
Access External Data in Real-time with Lightning Connect
Internet of things the salesforce lego machine cloud
Enterprise Architecture Salesforce
Ad

Similar to Building strong foundations apex enterprise patterns (20)

PDF
Intro to ColdBox MVC at Japan CFUG
PPTX
2011 NetUG HH: ASP.NET MVC & HTML 5
PDF
Apex Code Analysis Using the Tooling API and Canvas
PDF
td_mxc_rubyrails_shin
PDF
td_mxc_rubyrails_shin
PPTX
Modern ASP.NET Webskills
PPTX
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
PPTX
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
PDF
Javascript-heavy Salesforce Applications
PPTX
slides.pptx
PPTX
MVC by asp.net development company in india
PPTX
Testing a Service Fabric solution and live happy!!
PPTX
Getting started with MVC 5 and Visual Studio 2013
PPTX
DDD, CQRS and testing with ASP.Net MVC
PPTX
Mike Taulty MIX10 Silverlight Frameworks and Patterns
 
PPTX
Improving the Quality of Existing Software - DevIntersection April 2016
PPT
Tdd,Ioc
PPTX
It depends: Loving .NET Core dependency injection or not
PPTX
Intro to .NET for Government Developers
PDF
Top Testing Tips
Intro to ColdBox MVC at Japan CFUG
2011 NetUG HH: ASP.NET MVC & HTML 5
Apex Code Analysis Using the Tooling API and Canvas
td_mxc_rubyrails_shin
td_mxc_rubyrails_shin
Modern ASP.NET Webskills
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
Javascript-heavy Salesforce Applications
slides.pptx
MVC by asp.net development company in india
Testing a Service Fabric solution and live happy!!
Getting started with MVC 5 and Visual Studio 2013
DDD, CQRS and testing with ASP.Net MVC
Mike Taulty MIX10 Silverlight Frameworks and Patterns
 
Improving the Quality of Existing Software - DevIntersection April 2016
Tdd,Ioc
It depends: Loving .NET Core dependency injection or not
Intro to .NET for Government Developers
Top Testing Tips

Recently uploaded (20)

PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
L1 - Introduction to python Backend.pptx
PPTX
history of c programming in notes for students .pptx
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Nekopoi APK 2025 free lastest update
PPTX
Transform Your Business with a Software ERP System
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
top salesforce developer skills in 2025.pdf
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Online Work Permit System for Fast Permit Processing
PDF
AI in Product Development-omnex systems
PDF
Digital Strategies for Manufacturing Companies
Wondershare Filmora 15 Crack With Activation Key [2025
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
L1 - Introduction to python Backend.pptx
history of c programming in notes for students .pptx
ManageIQ - Sprint 268 Review - Slide Deck
PTS Company Brochure 2025 (1).pdf.......
Odoo POS Development Services by CandidRoot Solutions
Nekopoi APK 2025 free lastest update
Transform Your Business with a Software ERP System
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
top salesforce developer skills in 2025.pdf
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Understanding Forklifts - TECH EHS Solution
Online Work Permit System for Fast Permit Processing
AI in Product Development-omnex systems
Digital Strategies for Manufacturing Companies

Building strong foundations apex enterprise patterns

  • 1. Building Strong Foundations Apex Enterprise Patterns Andrew Fawcett FinancialForce.com, CTO @andyinthecloud
  • 2. About GREAT ALONE. BETTER TOGETHER. ‱ Native to Salesforce1ℱ Platform since 2009 ‱ Investors include Salesforce Ventures ‱ 650+ employees, San Francisco based 2
  • 3. Session Resources Follow the Session in the Dreamforce App, I will share this slide deck and other related links on the Feed Be social and feel free to ask follow up questions! 
  • 4. What's wrong with this picture?
  • 5. What's wrong with this picture? Developer “A” writes an Apex Controller first Developer “B” writes an Apex Batch job later.
  • 6. So what was wrong with that picture? Developer “A” Developer “B” MyControllerMyController Issue Use of ApexPages.currentPage() Unnecessary and fragile, utilize instead stdController.getId() method Error handling No try/catch error handling on controller method MyBatchJob Issue Use of ApexPages.currentPage() Is not available in a Batch Apex context, the constructor code will give an exception. SOQL Query and DML Governors Calling the controller method in a loop will cause a SOQL query and DML governor issues. Error Handling No try/catch error handling in the the execute method Separation of Concerns Developer A did not originally develop the controller logic expecting or anticipating Developer B’s would in the future try to reuse it from a Batch Context as well. They did not consider correct Separation of Concerns

  • 7. selectById selectByXXX queryLocatorById SOQL new DomainClass(
.) processRecords(
) Domain Class Service Class Selector Class QueryLocator start(
) execute(
) Finish(
) Batch Apex Service Boundary query queryquery Pattern Checklist Separation of Concerns ☐ Service Layer ☐ Domain Layer ☐ Selector Layer ☐
  • 8. So what is “Separation of Concerns” then? “The goal is to design systems so that functions can be optimized independently of other functions, so that failure of one function does not cause other functions to fail, and in general to make it easier to understand, design and manage complex interdependent systems” Wikipedia, “Separation of Concerns”
  • 9. Base Reference Material, Inspiration and Further Reading Service Layer Domain Layer ‱ Yet another Wrapper / Trigger pattern! Selector Layer Reference Martin Fowler ‱ http://martinfowler.com/eaaCatalog/ ‱ Author of “Patterns of Enterprise Application Architecture” Salesforce Wiki Reference ‱ http://wiki.developerforce.com/page/Apex_Enterprise_Patterns_-_Separation_of_Concerns
  • 10. Apex Enterprise Patterns Sample Application GitHub: financialforcedev/fflib-apex-common-samplecode
  • 11. Apex Enterprise Patterns Architecture selectById selectByXXX queryLocatorById SOQL new DomainClass(
.) processRecords(
) Domain Class Service Class Selector Class QueryLocator start(
) execute(
) Finish(
) Batch Apex Service Boundary query queryquery NOTE: You may also find Controllers consuming your Selector classes at times.
  • 12. Brief introduction to the Factory pattern
 ‱ In class-based programming, the factory method pattern is a creational pattern which uses factory methods to deal with the problem of creating objects without specifying the exact class of object that will be created. http://en.wikipedia.org/wiki/Factory_metho d_pattern
  • 13. With and without an Application Factory
 Without With - Just use new operator whenever - Simpler code base, no Apex Interfaces - No mocking support - No polymorphic domain - Adhoc Unit of Work configuration - Use Application class instead of new operator - Must use Apex Interfaces to define SOC - ApexMocks support - Ability to leverage Polymorphic Domains - Standardized Unit of Work throughout When creating instances of Service, Domain, Selector and Unit of Work classes

  • 14. Want to know more about Application factory? Just a regular class named Application with some public static final members in it! Further Reading
. Unit Testing, Apex Enterprise Patterns and ApexMocks – Part 1 Unit Testing, Apex Enterprise Patterns and ApexMocks – Part 2
  • 15. selectById selectByXXX queryLocatorById SOQL new DomainClass(
.) processRecords(
) Domain Class Service Class Selector Class QueryLocator start(
) execute(
) Finish(
) Batch Apex Service Boundary query queryquery Pattern Checklist Separation of Concerns  Service Layer ☐ Domain Layer ☐ Selector Layer ☐
  • 17. Introducing the Service Layer : Naming and Methods Naming Convention  Suffix with ‘Service’, e.g. OpportunitiesService  Methods named by purpose not usage, e.g. applyDiscounts  Stateless, uses with sharing and global optional for API readyness
  • 18. Introducing the Service Layer : Caller Benefits Clear Code Factoring  Encapsulates Processes / Tasks  Caller Context Agnostic, Controller class calling it example

  • 19. Introducing the Service Layer : Example Method Defined Responsibilities  Supports Bulkifcation  Transaction management
  • 20. Developing and calling a Service Layer Service Contract Developer “A” follows Service Layer pattern. Developer “A” writes Controller code to consume the Service. Developer “B” then reuses the Developer “A” code safely. AccountService.cls MyController.cls MyBatch.cls
  • 21. Code Walkthrough : Sample Services Managing DML and Transactions ‱ Unit of Work Pattern Classes OpportunitiesServiceImpl.cls
  • 22. Code Walkthrough : Custom Buttons Custom Buttons ‱ Detail and List View ‱ Calling Visualforce Controller Code Visualforce Controllers and Pages ‱ Error Handling ‱ Interacts with Service Layer ‱ Utilize bulkified methods ‱ Assume transaction containment ‱ Catch exceptions and display them on the page Classes and Pages OpportunityApplyDiscountController.cls ‱ opportunityapplydiscount.page ‱ opportunityapplydiscounts.page OpportunityCreateInvoiceController.cls ‱ opportunitycreateinvoice.page ‱ opportunitycreateinvoices.page
  • 23. Code Walkthrough : Batch Apex Classes CreatesInvoicesJob.cls  Error Handling  Interacts with Service Layer ‱ Utilize bulkified methods, Assume transaction containment ‱ Catch exceptions and logs them for later notification
  • 24. selectById selectByXXX queryLocatorById SOQL new DomainClass(
.) processRecords(
) Domain Class Service Class Selector Class QueryLocator start(
) execute(
) Finish(
) Batch Apex Service Boundary query queryquery Pattern Checklist Separation of Concerns  Service Layer  Domain Layer ☐ Selector Layer ☐
  • 25. Introducing the Domain Layer Domain Class Service Layer Visualforce Controller Apex Webservice Inbound Email Handler Batch Apex Scheduled Apex JavaScript Remo ng Apex Rest Service Class Domain Class Domain Class Domain Class Domain Layer Database Manipula on via Apex Trigger Service Opera ons via Apex Calls Custom Objects Standard UI Layouts Formulas Reports Dashboards Workflow Custom Object Custom Object Bulkifica on of DML Unit of Work Service Class Custom Object Service Class
  • 26. Introducing the Domain Layer Naming Convention  Name uses plural name of object, e.g. Opportunities NOTE: This class implements an interface and the newInstance method, required only if using Application factory
  • 27. Introducing the Domain Layer Clear Code Factoring  Encapsulates Validation / Defaulting of Fields  Wraps Apex Trigger Logic in Apex Class (Trigger/Wrapper Pattern)
  • 28. Introducing the Domain Layer Defined Responsibilities  Enforces Bulkifcation for logic  Platform security best practice (honors Users profile)  Encapsulates ALL logic / behavior for each object ‱ e.g. onValidate, onBeforeInsert and applyDiscount
  • 29. Introducing the Domain Layer : Apex Trigger Flow
  • 30. Code Walkthrough : Domain Layer : Apex Triggers What no code?!?  Triggers OpportunitiesTrigger.trigger OpportunityLineItemsTrigger.trigger
  • 31. selectById selectByXXX queryLocatorById SOQL new DomainClass(
.) processRecords(
) Domain Class Service Class Selector Class QueryLocator start(
) execute(
) Finish(
) Batch Apex Service Boundary query queryquery Pattern Checklist Separation of Concerns  Service Layer  Domain Layer  Selector Layer ☐
  • 32. Introducing the Selector Layer selectById selectByXXX queryLocatorById SOQL new DomainClass(
.) processRecords(
) Domain Class Service Class Selector Class QueryLocator start(
) execute(
) Finish(
) Batch Apex Service Boundary query queryquery NOTE: You may also find Controllers consuming your Selector classes at times.
  • 33. Introducing the Selector Layer Naming Convention  Plural object name suffixed by Selector ‱ e.g. OpportunitiesSelector NOTE: Interface and newInstance method not required if your not using the Application factory
  • 34. Introducing the Selector Layer Clear Code Factoring  Encapsulates Query Logic
  • 35. Introducing the Selector Layer Defined Responsibilities  Consistency over queried fields  Platform security best practice ‱ Configurable  Encapsulates ALL query logic
  • 36. Code Walkthrough : Selector Layer : Callers Service Layer Logic : OpportunitiesSelector.selectByIdWithProducts Domain Layer Logic : AccountsSelector.selectByOpportunity Apex Class OpportunitiesServiceImpl.cls Apex Class Opportunities.cls NOTE: Above example leverages feature of Selector factory
  • 37. selectById selectByXXX queryLocatorById SOQL new DomainClass(
.) processRecords(
) Domain Class Service Class Selector Class QueryLocator start(
) execute(
) Finish(
) Batch Apex Service Boundary query queryquery Pattern Checklist Separation of Concerns  Service Layer  Domain Layer  Selector Layer 
  • 40. When is SOC / DRY appropriate (a rough guide)? Solution / Code Base Size Developers Requirements Scope Number of Client Types and Interactions SOC/DRY Appropriate? Small 1 to 2 ‱ Well known and unlikely to change ‱ One off solutions ‱ Limited number of objects ‱ Standard UI ‱ Simple VF / Triggers ‱ No Batch Mode ‱ No API ‱ No Mobile Typically not Small to Medium 1 to 6 ‱ Well known but may need to evolve rapidly ‱ Growing number objects and processes interacting ‱ Product deliverable or larger duration projects ‱ Standard UI ‱ Advanced VF / JQuery ‱ Batch Mode ‱ API (on roadmap) ‱ Mobile (on roadmap) Worth considering Large > 6 ‱ Scope driven by multiple customers and user types ‱ Large number of objects ‱ Generic product or solution aimed at Mid to Enterprise market with Customer or Partner Integrations. ‱ Growing development team! ‱ Standard UI ‱ Advanced VF / JQuery ‱ Batch Mode ‱ Developer / Partner API ‱ Mobile Clients ‱ New Platform Feature Ready, Chatter Actions! Definite benifits
  • 41. Session Resources Follow the Session in the Dreamforce App, I will share this slide deck and other related links on the Feed Be social and feel free to ask follow up questions! 
  • 43. 3 Earn a GoPro prize entry for each completed survey Tap the bell to take a survey2Enroll in a session1 Share Your Feedback, and Win a GoPro!

Editor's Notes

  • #6: 1 – 5 mins
  • #9: 1 – 10 mins
  • #15: Insert links and picture of my blog article
  • #17: Need a new diagram to show AuraEnabled, Queables etc
  • #21: 1 – 5 mins