building strong foundations apex enterprise patterns

43
Building Strong Foundations Apex Enterprise Patterns Andrew Fawcett FinancialForce.com, CTO @andyinthecloud

Upload: andyinthecloud

Post on 09-Apr-2017

1.315 views

Category:

Software


8 download

TRANSCRIPT

Page 1: Building strong foundations apex enterprise patterns

Building Strong Foundations Apex Enterprise PatternsAndrew FawcettFinancialForce.com, CTO@andyinthecloud

Page 2: Building strong foundations apex enterprise patterns

About

GREAT ALONE. BETTER TOGETHER.• Native to Salesforce1™ Platform

since 2009• Investors include Salesforce Ventures• 650+ employees, San Francisco based

2

Page 3: Building strong foundations apex enterprise patterns

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!

Page 4: Building strong foundations apex enterprise patterns

What's wrong with this picture?

Page 5: Building strong foundations apex enterprise patterns

What's wrong with this picture?

Developer “A” writes an Apex Controller first

Developer “B” writes an Apex Batch job later.

Page 6: Building strong foundations apex enterprise patterns

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…

Page 7: Building strong foundations apex enterprise patterns

Pattern ChecklistSeparation of Concerns ☐Service Layer ☐Domain Layer ☐Selector Layer ☐

Page 8: Building strong foundations apex enterprise patterns

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”

Page 9: Building strong foundations apex enterprise patterns

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

Page 10: Building strong foundations apex enterprise patterns

Apex Enterprise Patterns Sample Application

GitHub: financialforcedev/fflib-apex-common-samplecode

Page 11: Building strong foundations apex enterprise patterns

Apex Enterprise Patterns Architecture

NOTE: You may also find Controllers consuming your Selector classes at times.

Page 12: Building strong foundations apex enterprise patterns

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

Page 13: Building strong foundations apex enterprise patterns

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…

Page 15: Building strong foundations apex enterprise patterns

Pattern ChecklistSeparation of Concerns Service Layer ☐Domain Layer ☐Selector Layer ☐

Page 16: Building strong foundations apex enterprise patterns

Introducing the Service Layer

Page 17: Building strong foundations apex enterprise patterns

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

Page 18: Building strong foundations apex enterprise patterns

Introducing the Service Layer : Caller Benefits

Clear Code Factoring Encapsulates Processes / Tasks Caller Context Agnostic, Controller class calling it example…

Page 19: Building strong foundations apex enterprise patterns

Introducing the Service Layer : Example Method

Defined Responsibilities Supports Bulkifcation Transaction management

Page 20: Building strong foundations apex enterprise patterns

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

Page 21: Building strong foundations apex enterprise patterns

Code Walkthrough : Sample Services Managing DML and Transactions• Unit of Work Pattern

Classes

OpportunitiesServiceImpl.cls

Page 22: Building strong foundations apex enterprise patterns

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

Page 23: Building strong foundations apex enterprise patterns

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

Page 24: Building strong foundations apex enterprise patterns

Pattern ChecklistSeparation of Concerns Service Layer Domain Layer ☐Selector Layer ☐

Page 25: Building strong foundations apex enterprise patterns

Introducing the Domain Layer

Page 26: Building strong foundations apex enterprise patterns

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

Page 27: Building strong foundations apex enterprise patterns

Introducing the Domain Layer

Clear Code Factoring Encapsulates Validation

/ Defaulting of Fields Wraps Apex Trigger Logic

in Apex Class (Trigger/Wrapper Pattern)

Page 28: Building strong foundations apex enterprise patterns

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

Page 29: Building strong foundations apex enterprise patterns

Introducing the Domain Layer : Apex Trigger Flow

Page 30: Building strong foundations apex enterprise patterns

Code Walkthrough : Domain Layer : Apex Triggers What no code?!? Triggers

OpportunitiesTrigger.triggerOpportunityLineItemsTrigger.trigger

Page 31: Building strong foundations apex enterprise patterns

Pattern ChecklistSeparation of Concerns Service Layer Domain Layer Selector Layer ☐

Page 32: Building strong foundations apex enterprise patterns

Introducing the Selector Layer

NOTE: You may also find Controllers consuming your Selector classes at times.

Page 33: Building strong foundations apex enterprise patterns

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

Page 34: Building strong foundations apex enterprise patterns

Introducing the Selector LayerClear Code Factoring

Encapsulates Query Logic

Page 35: Building strong foundations apex enterprise patterns

Introducing the Selector Layer

Defined Responsibilities Consistency over queried fields Platform security best practice

• Configurable

Encapsulates ALL query logic

Page 36: Building strong foundations apex enterprise patterns

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

Page 37: Building strong foundations apex enterprise patterns

Pattern ChecklistSeparation of Concerns Service Layer Domain Layer Selector Layer

Page 38: Building strong foundations apex enterprise patterns

Summary

Page 39: Building strong foundations apex enterprise patterns

Summary

Page 40: Building strong foundations apex enterprise patterns

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

Page 41: Building strong foundations apex enterprise patterns

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!

Page 42: Building strong foundations apex enterprise patterns
Page 43: Building strong foundations apex enterprise patterns

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!