SlideShare uma empresa Scribd logo
1 de 43
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!

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!

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Lightning web components - Episode 1 - An Introduction
Lightning web components - Episode 1 - An IntroductionLightning web components - Episode 1 - An Introduction
Lightning web components - Episode 1 - An Introduction
 
Introduction to the Salesforce Security Model
Introduction to the Salesforce Security ModelIntroduction to the Salesforce Security Model
Introduction to the Salesforce Security Model
 
Salesforce Service Cloud
Salesforce Service CloudSalesforce Service Cloud
Salesforce Service Cloud
 
Lightning web components
Lightning web componentsLightning web components
Lightning web components
 
SalesforceにおけるCDC(変更データキャプチャ)の実装・活用法について
SalesforceにおけるCDC(変更データキャプチャ)の実装・活用法についてSalesforceにおけるCDC(変更データキャプチャ)の実装・活用法について
SalesforceにおけるCDC(変更データキャプチャ)の実装・活用法について
 
Introduction to lightning Web Component
Introduction to lightning Web ComponentIntroduction to lightning Web Component
Introduction to lightning Web Component
 
Integrating with salesforce using platform events
Integrating with salesforce using platform eventsIntegrating with salesforce using platform events
Integrating with salesforce using platform events
 
Salesforce Field Service Lightning
Salesforce Field Service LightningSalesforce Field Service Lightning
Salesforce Field Service Lightning
 
Lightning web components
Lightning web components Lightning web components
Lightning web components
 
Salesforce Community Cloud
Salesforce Community CloudSalesforce Community Cloud
Salesforce Community Cloud
 
Deep Dive into Apex Triggers
Deep Dive into Apex TriggersDeep Dive into Apex Triggers
Deep Dive into Apex Triggers
 
Salesforce Service Cloud Training | Salesforce Training For Beginners - Servi...
Salesforce Service Cloud Training | Salesforce Training For Beginners - Servi...Salesforce Service Cloud Training | Salesforce Training For Beginners - Servi...
Salesforce Service Cloud Training | Salesforce Training For Beginners - Servi...
 
Session 1: INTRODUCTION TO SALESFORCE
Session 1: INTRODUCTION TO SALESFORCESession 1: INTRODUCTION TO SALESFORCE
Session 1: INTRODUCTION TO SALESFORCE
 
An Introduction to Lightning Web Components
An Introduction to Lightning Web ComponentsAn Introduction to Lightning Web Components
An Introduction to Lightning Web Components
 
Platform Events by Tim Taylor
Platform Events by Tim TaylorPlatform Events by Tim Taylor
Platform Events by Tim Taylor
 
Introduction to Apex for Developers
Introduction to Apex for DevelopersIntroduction to Apex for Developers
Introduction to Apex for Developers
 
Simplifying the Complexity of Salesforce CPQ: Tips & Best Practices
Simplifying the Complexity of Salesforce CPQ: Tips & Best PracticesSimplifying the Complexity of Salesforce CPQ: Tips & Best Practices
Simplifying the Complexity of Salesforce CPQ: Tips & Best Practices
 
Salesforce Application Lifecycle Management presented to EA Forum by Sam Garf...
Salesforce Application Lifecycle Management presented to EA Forum by Sam Garf...Salesforce Application Lifecycle Management presented to EA Forum by Sam Garf...
Salesforce Application Lifecycle Management presented to EA Forum by Sam Garf...
 
Introducing the Salesforce platform
Introducing the Salesforce platformIntroducing the Salesforce platform
Introducing the Salesforce platform
 
Integrating with salesforce
Integrating with salesforceIntegrating with salesforce
Integrating with salesforce
 

Destaque

Destaque (19)

Salesforce World Tour 2016 : Lightning Out : Components on any Platform
Salesforce World Tour 2016 : Lightning Out : Components on any PlatformSalesforce World Tour 2016 : Lightning Out : Components on any Platform
Salesforce World Tour 2016 : Lightning Out : Components on any Platform
 
Apex Design Patterns
Apex Design PatternsApex Design Patterns
Apex Design Patterns
 
Introduction to Analytics Cloud
Introduction to Analytics CloudIntroduction to Analytics Cloud
Introduction to Analytics Cloud
 
Real-time SQL Access to Your Salesforce.com Data Using Progress Data Direct
Real-time SQL Access to Your Salesforce.com Data Using Progress Data DirectReal-time SQL Access to Your Salesforce.com Data Using Progress Data Direct
Real-time SQL Access to Your Salesforce.com Data Using Progress Data Direct
 
Apex Connector for Lightning Connect: Make Anything a Salesforce Object
Apex Connector for Lightning Connect: Make Anything a Salesforce ObjectApex Connector for Lightning Connect: Make Anything a Salesforce Object
Apex Connector for Lightning Connect: Make Anything a Salesforce Object
 
Lightning strikes twice- SEDreamin
Lightning strikes twice- SEDreaminLightning strikes twice- SEDreamin
Lightning strikes twice- SEDreamin
 
Force.com Canvas in the Publisher and Chatter Feed
Force.com Canvas in the Publisher and Chatter FeedForce.com Canvas in the Publisher and Chatter Feed
Force.com Canvas in the Publisher and Chatter Feed
 
Go Faster with Process Builder
Go Faster with Process BuilderGo Faster with Process Builder
Go Faster with Process Builder
 
Lightning Connect: Lessons Learned
Lightning Connect: Lessons LearnedLightning Connect: Lessons Learned
Lightning Connect: Lessons Learned
 
Lightning Out: Components for the Rest of the World
Lightning Out: Components for the Rest of the WorldLightning Out: Components for the Rest of the World
Lightning Out: Components for the Rest of the World
 
Lightning Connect Custom Adapters: Connecting Anything with Salesforce
Lightning Connect Custom Adapters: Connecting Anything with SalesforceLightning Connect Custom Adapters: Connecting Anything with Salesforce
Lightning Connect Custom Adapters: Connecting Anything with Salesforce
 
Two-Way Integration with Writable External Objects
Two-Way Integration with Writable External ObjectsTwo-Way Integration with Writable External Objects
Two-Way Integration with Writable External Objects
 
Design Patterns for Asynchronous Apex
Design Patterns for Asynchronous ApexDesign Patterns for Asynchronous Apex
Design Patterns for Asynchronous Apex
 
Apex collection patterns
Apex collection patternsApex collection patterns
Apex collection patterns
 
Apex Design Patterns
Apex Design PatternsApex Design Patterns
Apex Design Patterns
 
Secure Salesforce: Lightning Components Best Practices
Secure Salesforce: Lightning Components Best PracticesSecure Salesforce: Lightning Components Best Practices
Secure Salesforce: Lightning Components Best Practices
 
Access External Data in Real-time with Lightning Connect
Access External Data in Real-time with Lightning ConnectAccess External Data in Real-time with Lightning Connect
Access External Data in Real-time with Lightning Connect
 
Internet of things the salesforce lego machine cloud
Internet of things   the salesforce lego machine cloudInternet of things   the salesforce lego machine cloud
Internet of things the salesforce lego machine cloud
 
Enterprise Architecture Salesforce
Enterprise Architecture SalesforceEnterprise Architecture Salesforce
Enterprise Architecture Salesforce
 

Semelhante a Building strong foundations apex enterprise patterns

td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
tutorialsruby
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
tutorialsruby
 

Semelhante a Building strong foundations apex enterprise patterns (20)

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

Último

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 

Último (20)

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 

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! 
  • 42.
  • 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!

Notas do Editor

  1. 1 – 5 mins
  2. 1 – 10 mins
  3. Insert links and picture of my blog article
  4. Need a new diagram to show AuraEnabled, Queables etc
  5. 1 – 5 mins