1
Apex
Enterprise
Patterns
Galore!
Boston Salesforce Developers Group
Marty Chang, Solution Architect – Slalom
Peter Yao, Senior Director, Products – BlueWave Solar
June 27, 2019
2
Agenda • Welcome!
• Why are we here?
• Best Practices & Demos
o Triggers, DML, Tests
o Controllers (LWC, Aura, VF) & SOQL
o Callouts
o Batchable & Schedulable jobs
• Takeaways
June 2019 Boston Salesforce Dev Group Meeting
3
Welcome!
4
Slalom is a modern consulting firm
focused on strategy, technology, and
business transformation.
Slalom is a modern consulting firm
focused on strategy, technology, and
business transformation.
5
strategy
Redefine what’s possible
Go beyond the expected. We help you move confidently through
ambiguity and risk, focus on your customer needs, and deliver
sustainable business value.
technology
We analyze, architect, and co-create
Learn from your data, create incredible digital experiences, or make
the most of new tech. We blend design, engineering, and analytics
expertise to help you build the future.
transformation
We deliver with you
New technologies. Shifting customers. Industry disruption. Business
moves fast, and we specialize in working through change with you.
Whatwedo
We bring impactful customer
experiences to life quickly
2,250+
Salesforce certifications
949
Projects for 318
clients in 2018
600+
Consultants with
Salesforce
experience
Platinum Consulting Partner
2x Partner Innovation Award Winner
Sales Cloud
Service Cloud
Community Cloud
Analytics Cloud
Einstein
Field Service
Marketing Cloud
Configure, Price, Quote (CPQ)
MuleSoft
Competencies
6
We believe in a world in which every
person loves their work and life.
We put
people first.
7
We are a B Corp on a mission to revolutionize energy with
simple, powerful solar solutions.
8
WHAT WE DO
88
HOME SOLAR LOANS COMMUNITY SOLAR SOLAR DEVELOPMENT
Improves solar financing
accessibility for
households with
viable rooftops.
Expands access to solar
for residents and small
businesses, regardless of
roof viability.
Provides environmental
and economic value by
developing large scale
community solar arrays.
9
Why are we
here?
June 2019 Boston Salesforce Dev Group Meeting
10
Several new developers introduced to the
team
Big classes, especially tests
Distinct user stories require updating the
same class resulting in merge conflicts
Most business logic initiated by trigger
Frequent encounters with governor limits
Duplicated code
Ø Where to start development?
Ø How to identify bug root cause?
A typical
problem
• Lines of code:
• 75k in .cls
• 12k in .cmp
• 12k in .js
• 4k in .page
• 500 in .trigger
June 2019 Boston Salesforce Dev Group Meeting
11
Separation of Concerns
Base Size of
Solution or Code
Number of
Developers
Requirements Scope Number of Client Types & Interactions SOC
Appropriate?
Small 1 to 2 •Well known and unlikely to change
•One-off solutions
•Limited number of objects
•Standard UI
•Simple UI / 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 of objects and processing interactions
•Product deliverable or larger duration projects
•Standard UI
•Advanced VF / Lightning
•Batch Mode
•API (on roadmap)
•Mobile (on roadmap)
Worth
considering
Large > 6 •Scope driven by multiple customer 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 / Lightning
•Batch Mode
•Developer / Partner API
•Mobile Clients
•New Platform Feature Ready, Chatter Actions!
Definite benefits
https://trailhead.salesforce.com/en/content/learn/modules/apex_patterns_sl/apex_patterns_sl_soc
June 2019 Boston Salesforce Dev Group Meeting
12
12
Financial Force Apex Common: https://github.com/financialforcedev/fflib-apex-common/
Well Documented:
Actively discussed:
WHAT WE LIKED
Actively updated:
13
13
WHAT WE DIDN’T LIKE
Heavyweight:
Hard for us to use it all from the start, especially ApexMocks
The light-version fork is a few years old:
14
Performing SOQL and DML in
tests is expensive … and adds to
the overall time it takes to execute
all application tests, which
becomes important once you start
to consider Continuous
Integration.
Andrew Fawcett
Author of Force.com Enterprise Architecture
15
Build with unit tests in mind
June 2019 Boston Salesforce Dev Group Meeting
Considerations
• Salesforce requires code coverage for all Apex.
• 100% code coverage is a byproduct of well written tests.
• Unit tests are a first-order concern.
Responsibilities
• Every Apex class should have a corresponding test class.
• Mocks should be used to ensure that unit tests in a test class
only exercise the functions and methods within the
associated class.
• Integration tests should ideally exist separately from unit
tests, to reduce the time to run local tests for CI/CD.
16
What if triggers looked more like workflow rules?
Trigger “workflows”
June 2019 Boston Salesforce Dev Group Meeting
Considerations
• Trigger context variables are only available in the context of
a running DML operation.
• Recursion can get messy, across triggers, workflow rules
and Lightning processes (i.e., processes created with
Lightning Process Builder).
Responsibilities
• Evaluate entry criteria.
• Execute actions.
• Keep Trigger context variable references exclusively in
.trigger files.
17
Workflow Concept Trigger Workflow Concept
Object TriggerWorkflow__mdt.SobjectName__c
Rule Name Apex class name ending with Workflow
Description Apex class comment block
Evaluate the rule when a record is "created" or
"created, and every time it's edited"
TriggerWorkflow__mdt.IsOnInsert__c and
TriggerWorkflow__mdt.IsOnUpdate__c
Evaluate the rule when a record is "created, and
any time it's edited to subsequently meet criteria"
TriggerWorkflow__mdt.IsOnInsert__c and
TriggerWorkflow__mdt.IsOnUpdate__c with
custom logic in the workflow's qualify method
Rule Criteria Custom logic in the workflow's qualify method
Active TriggerWorkflow__mdt.IsActive__c
Workflow Actions
executeBefore() and executeAfter()
methods in the workflow class
18
19
Trigger Workflow
20
Why not have a “DJ” in your org harmonizing your data?
DatabaseJockey
June 2019 Boston Salesforce Dev Group Meeting
Considerations
• Reduce time to run local tests by minimizing the number of
Apex tests which execute DML operations.
Responsibilities
• Insert, update, delete, undelete SObject records.
• Be the only Apex class which performs DML operations.
21
22
23
24
25
26
27
28
Just an interface between the user and all available services
Controllers (LWC, Aura, VF)
June 2019 Boston Salesforce Dev Group Meeting
Considerations
• Different options for returning errors to the end-user
• Sharing (CRUD, FLS, record-level) is not enforced by default
• (VF) May need to maintain state of the end-user application
Responsibilities
• Call a single Service class to execute business logic
• Manage anything specific to the client or user interface
• Error handling
• Enforcing sharing
• If simple enough, replace with Lightning Data Service (or
Visualforce Remote Objects)
29
One query to rule them all (no matter where called from)
SOQL
June 2019 Boston Salesforce Dev Group Meeting
Considerations
• Introduces dependency on database fields & objects
• Records queried may be shared in different functions, with
different data populated
• By default, sharing (CRUD, FLS, record-level) is based on the
running user
Responsibilities
• Provide a predictable set of fields and order of records returned
• Ensure data is queried only when necessary (aka once)
• Control access to related object fields using wrapper classes
30
Share your services or take advantage of others’
Callouts (Inbound & Outbound)
June 2019 Boston Salesforce Dev Group Meeting
Considerations
• Security for accessing the endpoint and the data returned
• Versioning & backwards compatibility
• Order of operations with DML
Responsibilities
• Abstract callouts in separate classes to avoid tight dependencies
• Isolate external-facing Apex REST classes from the Service classes
they delegate to
• Handle exceptions and error messages appropriately
31
Takeaways
June 2019 Boston Salesforce Dev Group Meeting
• You don’t have to start from scratch.
• Establish a pattern and stick with it.
• Expect your pattern to change.
• Expect inconsistencies in your code base as your patterns
continue to evolve over time.
• Even if it’s by yourself, create a style guide and think about it
as you go. You can have plenty of interesting conversations
with your past self and your future self!
32
Thank you!

Apex Enterprise Patterns Galore - Boston, MA dev group meeting 062719

  • 1.
    1 Apex Enterprise Patterns Galore! Boston Salesforce DevelopersGroup Marty Chang, Solution Architect – Slalom Peter Yao, Senior Director, Products – BlueWave Solar June 27, 2019
  • 2.
    2 Agenda • Welcome! •Why are we here? • Best Practices & Demos o Triggers, DML, Tests o Controllers (LWC, Aura, VF) & SOQL o Callouts o Batchable & Schedulable jobs • Takeaways June 2019 Boston Salesforce Dev Group Meeting
  • 3.
  • 4.
    4 Slalom is amodern consulting firm focused on strategy, technology, and business transformation. Slalom is a modern consulting firm focused on strategy, technology, and business transformation.
  • 5.
    5 strategy Redefine what’s possible Gobeyond the expected. We help you move confidently through ambiguity and risk, focus on your customer needs, and deliver sustainable business value. technology We analyze, architect, and co-create Learn from your data, create incredible digital experiences, or make the most of new tech. We blend design, engineering, and analytics expertise to help you build the future. transformation We deliver with you New technologies. Shifting customers. Industry disruption. Business moves fast, and we specialize in working through change with you. Whatwedo We bring impactful customer experiences to life quickly 2,250+ Salesforce certifications 949 Projects for 318 clients in 2018 600+ Consultants with Salesforce experience Platinum Consulting Partner 2x Partner Innovation Award Winner Sales Cloud Service Cloud Community Cloud Analytics Cloud Einstein Field Service Marketing Cloud Configure, Price, Quote (CPQ) MuleSoft Competencies
  • 6.
    6 We believe ina world in which every person loves their work and life. We put people first.
  • 7.
    7 We are aB Corp on a mission to revolutionize energy with simple, powerful solar solutions.
  • 8.
    8 WHAT WE DO 88 HOMESOLAR LOANS COMMUNITY SOLAR SOLAR DEVELOPMENT Improves solar financing accessibility for households with viable rooftops. Expands access to solar for residents and small businesses, regardless of roof viability. Provides environmental and economic value by developing large scale community solar arrays.
  • 9.
    9 Why are we here? June2019 Boston Salesforce Dev Group Meeting
  • 10.
    10 Several new developersintroduced to the team Big classes, especially tests Distinct user stories require updating the same class resulting in merge conflicts Most business logic initiated by trigger Frequent encounters with governor limits Duplicated code Ø Where to start development? Ø How to identify bug root cause? A typical problem • Lines of code: • 75k in .cls • 12k in .cmp • 12k in .js • 4k in .page • 500 in .trigger June 2019 Boston Salesforce Dev Group Meeting
  • 11.
    11 Separation of Concerns BaseSize of Solution or Code Number of Developers Requirements Scope Number of Client Types & Interactions SOC Appropriate? Small 1 to 2 •Well known and unlikely to change •One-off solutions •Limited number of objects •Standard UI •Simple UI / 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 of objects and processing interactions •Product deliverable or larger duration projects •Standard UI •Advanced VF / Lightning •Batch Mode •API (on roadmap) •Mobile (on roadmap) Worth considering Large > 6 •Scope driven by multiple customer 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 / Lightning •Batch Mode •Developer / Partner API •Mobile Clients •New Platform Feature Ready, Chatter Actions! Definite benefits https://trailhead.salesforce.com/en/content/learn/modules/apex_patterns_sl/apex_patterns_sl_soc June 2019 Boston Salesforce Dev Group Meeting
  • 12.
    12 12 Financial Force ApexCommon: https://github.com/financialforcedev/fflib-apex-common/ Well Documented: Actively discussed: WHAT WE LIKED Actively updated:
  • 13.
    13 13 WHAT WE DIDN’TLIKE Heavyweight: Hard for us to use it all from the start, especially ApexMocks The light-version fork is a few years old:
  • 14.
    14 Performing SOQL andDML in tests is expensive … and adds to the overall time it takes to execute all application tests, which becomes important once you start to consider Continuous Integration. Andrew Fawcett Author of Force.com Enterprise Architecture
  • 15.
    15 Build with unittests in mind June 2019 Boston Salesforce Dev Group Meeting Considerations • Salesforce requires code coverage for all Apex. • 100% code coverage is a byproduct of well written tests. • Unit tests are a first-order concern. Responsibilities • Every Apex class should have a corresponding test class. • Mocks should be used to ensure that unit tests in a test class only exercise the functions and methods within the associated class. • Integration tests should ideally exist separately from unit tests, to reduce the time to run local tests for CI/CD.
  • 16.
    16 What if triggerslooked more like workflow rules? Trigger “workflows” June 2019 Boston Salesforce Dev Group Meeting Considerations • Trigger context variables are only available in the context of a running DML operation. • Recursion can get messy, across triggers, workflow rules and Lightning processes (i.e., processes created with Lightning Process Builder). Responsibilities • Evaluate entry criteria. • Execute actions. • Keep Trigger context variable references exclusively in .trigger files.
  • 17.
    17 Workflow Concept TriggerWorkflow Concept Object TriggerWorkflow__mdt.SobjectName__c Rule Name Apex class name ending with Workflow Description Apex class comment block Evaluate the rule when a record is "created" or "created, and every time it's edited" TriggerWorkflow__mdt.IsOnInsert__c and TriggerWorkflow__mdt.IsOnUpdate__c Evaluate the rule when a record is "created, and any time it's edited to subsequently meet criteria" TriggerWorkflow__mdt.IsOnInsert__c and TriggerWorkflow__mdt.IsOnUpdate__c with custom logic in the workflow's qualify method Rule Criteria Custom logic in the workflow's qualify method Active TriggerWorkflow__mdt.IsActive__c Workflow Actions executeBefore() and executeAfter() methods in the workflow class
  • 18.
  • 19.
  • 20.
    20 Why not havea “DJ” in your org harmonizing your data? DatabaseJockey June 2019 Boston Salesforce Dev Group Meeting Considerations • Reduce time to run local tests by minimizing the number of Apex tests which execute DML operations. Responsibilities • Insert, update, delete, undelete SObject records. • Be the only Apex class which performs DML operations.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
    28 Just an interfacebetween the user and all available services Controllers (LWC, Aura, VF) June 2019 Boston Salesforce Dev Group Meeting Considerations • Different options for returning errors to the end-user • Sharing (CRUD, FLS, record-level) is not enforced by default • (VF) May need to maintain state of the end-user application Responsibilities • Call a single Service class to execute business logic • Manage anything specific to the client or user interface • Error handling • Enforcing sharing • If simple enough, replace with Lightning Data Service (or Visualforce Remote Objects)
  • 29.
    29 One query torule them all (no matter where called from) SOQL June 2019 Boston Salesforce Dev Group Meeting Considerations • Introduces dependency on database fields & objects • Records queried may be shared in different functions, with different data populated • By default, sharing (CRUD, FLS, record-level) is based on the running user Responsibilities • Provide a predictable set of fields and order of records returned • Ensure data is queried only when necessary (aka once) • Control access to related object fields using wrapper classes
  • 30.
    30 Share your servicesor take advantage of others’ Callouts (Inbound & Outbound) June 2019 Boston Salesforce Dev Group Meeting Considerations • Security for accessing the endpoint and the data returned • Versioning & backwards compatibility • Order of operations with DML Responsibilities • Abstract callouts in separate classes to avoid tight dependencies • Isolate external-facing Apex REST classes from the Service classes they delegate to • Handle exceptions and error messages appropriately
  • 31.
    31 Takeaways June 2019 BostonSalesforce Dev Group Meeting • You don’t have to start from scratch. • Establish a pattern and stick with it. • Expect your pattern to change. • Expect inconsistencies in your code base as your patterns continue to evolve over time. • Even if it’s by yourself, create a style guide and think about it as you go. You can have plenty of interesting conversations with your past self and your future self!
  • 32.