Building strong foundations apex enterprise patterns
-
Upload
andyinthecloud -
Category
Software
-
view
1.317 -
download
8
Transcript of Building strong foundations apex enterprise patterns
Building Strong Foundations Apex Enterprise PatternsAndrew FawcettFinancialForce.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 IssueUse of ApexPages.currentPage() Unnecessary and fragile, utilize instead
stdController.getId() method
Error handling No try/catch error handling on controller method
MyBatchJob IssueUse 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 methodSeparation 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…
Pattern ChecklistSeparation 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
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_method_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 1Unit Testing, Apex Enterprise Patterns and ApexMocks – Part 2
Pattern ChecklistSeparation of Concerns Service Layer ☐Domain Layer ☐Selector Layer ☐
Introducing the Service Layer
Introducing the Service Layer : Naming and MethodsNaming 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 PagesOpportunityApplyDiscountController.cls
• opportunityapplydiscount.page
• opportunityapplydiscounts.page
OpportunityCreateInvoiceController.cls
• opportunitycreateinvoice.page
• opportunitycreateinvoices.page
Code Walkthrough : Batch ApexClasses
CreatesInvoicesJob.cls
Error Handling Interacts with Service Layer
• Utilize bulkified methods, Assume transaction containment• Catch exceptions and logs them for later notification
Pattern ChecklistSeparation of Concerns Service Layer Domain Layer ☐Selector Layer ☐
Introducing the Domain Layer
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.triggerOpportunityLineItemsTrigger.trigger
Pattern ChecklistSeparation of Concerns Service Layer Domain Layer Selector Layer ☐
Introducing the Selector Layer
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 LayerClear 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
Pattern ChecklistSeparation 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 surveyTap the bell to take a survey2Enroll in a session1
Share Your Feedback, and Win a GoPro!