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!
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…
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
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
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
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
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
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
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 – 5 mins
1 – 10 mins
Insert links and picture of my blog article
Need a new diagram to show AuraEnabled, Queables etc