1. Apex Triggers & Scheduler Frameworks
By
Sumitkumar Shingavi
@sumit.shingavi
2. Agenda
Design discussion on
Apex Trigger
Batches / Schedulers
Open house : Share your experience!
Twitter handlers: @sumit.shingavi @Prasanna
@thisisnotapril @salesforceDevs @TheChrisDuarte
@kevindrapatel
3. Few Questions : Apex Triggers
When to use apex triggers?
When to use before / after trigger?
How many triggers you have built so far?
What is the pattern of code you have used?
What is batch size a trigger can handle when
bulkified?
Do you ever seen a need to de-activate your triggers
during historic data migration for enterprise scale
projects?
4. 3 ways to write Apex triggers?
Modular Programming Approach – Simplest! (70%)
Factory Pattern (20%)
Abstraction of Handlers (10%)
When there are multiple handlers for a object
Sequencing of handlers is required in execution
Dynamic instance creation is required.
CustomSettings__c cs = CustomSettings__c.getInstance('Vehicle');
Type t = Type.forName(cs.className__c);
Vehicle v = (Vehicle) t.newInstance();
5. Apex Triggers – Keep it Simple!
ONE trigger per object
Logic – less triggers
Context specific handler methods
Use advance inline queried for loops wherever possible
Right naming conventions
Entry criteria – No open entry points / method calls!
For Modular Programming approach, follow structure as:
AccountTrigger
AccountTriggerHandler
AccountTriggerActions
AccountTriggerTest
For code visit: https://cloudmastro.blogspot.com
6. Factory & Abstraction of Handlers
Factory pattern
You should have an interface which declares all handler
virtual methods
Handlers are instantiated dynamically
When it actual goes down, you need to pass 1 object at a
time by iterating over List<sObject>
Abstractions of handlers
Also called as Dispatcher pattern
Used when you want heavy segregation between your
events
Difficult to maintain
7. Advantages of Proposed Framework
Order of execution
Separation of concerns
Control over re-entrant code
Clear organization and structure
Singleton frame
Make implementing new logic very easy
Simplify testing and maintenance
What not to do!
Do not use static variables to control re-entrant code
8. Apex Scheduled Batch Apex : Quick Highs
You can have a single class Schedulable and Batchable
Default batch size is 200 but can be raised up to 2000
It is asynchronous so no guarantee on time
100 scheduled apex jobs at a time
While writing unit tests; you should put asserts after
Test.stopTest()
Governor limits applied separately for batch and schedule
10 webservice callouts per batch
Database.stateful, Apex Flex Queue (100 jobs in one shot)
Serial Batches: For this, you need to call next batch in
final() method of current batch.