new String[] {"hip”, "hip”}; (hip hip array!) Q: What’s the object-oriented way to become wealthy? A: Inheritance To understand what recursion is, you must first understand recursion. Q: Why don't jokes work in octal? A: Because 7 10 11 Session: Write Bulletproof Trigger Code
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
new String[] {"hip”, "hip”};
(hip hip array!)
Q: What’s the object-oriented way to become wealthy?
A: Inheritance
To understand what recursion is, you must first understand recursion.
Writing Apex triggers can be simple, safe, and fun!
Safe harbor statement under the Private Securities Litigation Reform Act of 1995:
This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results expressed or implied by the forward-looking statements we make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of product or service availability, subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services.
The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our service, new products and services, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the outcome of any litigation, risks associated with completed and any possible mergers and acquisitions, the immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our annual report on Form 10-K for the most recent fiscal year and in our quarterly report on Form 10-Q for the most recent fiscal quarter. These documents and others containing important disclosures are available on the SEC Filings section of the Investor Information section of our Web site.
Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available. Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.
Safe Harbor
Steve Cox Senior Software Developer, Exponent Partners
1. What are the “bullets”?
a) Pop Quiz
b) What makes trigger writing challenging?
2. What’s our defense?!
a) Don’t write a trigger
b) Avoid DML
c) Write great unit tests
d) Use a good trigger framework
Agenda
1. // When an account changes, set the description on all contacts associated with that account2. trigger MyAccountTrigger on Account(before insert, before update) {3. Account a = Trigger.new[0];4. Contact[] contacts = [SELECT Salutation, FirstName FROM Contact WHERE AccountId = :a.Id];
11. //TODO assert descriptions ARE set12. }13. . . .
Test the trigger Write Great Unit Tests
Dealing with “Bullets” Defense #4: Use a Good Trigger Framework
A framework can provide consistency and save loads of time
• Allows you to specify the processing order
• Makes enabling/disabling individual handlers a snap
• Provides centralized diagnostics and error handling
• Decreases development and ramp-up time
Use a Good Trigger Framework
Framework Features Use a Good Trigger Framework
1. trigger MyObj on MyObj__c(after delete, after insert, after undelete,2. after update, before delete, before insert, before update) {3. new TriggerFactory().handle(MyObj__c.SObjectType); // non-testable / non-reusable code4. }
// Trigger body is reduced to a single line
1. public static Handler__c[] handlers {2. get {3. if (null == handlers) {4. handlers = [SELECT ... FROM TriggerSettings WHERE Active__c = true ORDER BY Type__c, Order__c];5. //categorize as desired – SObjectType, subsystem, feature, etc.6. }7. return handlers;8. }
9. private set;10. }
// Handlers are declared in custom settings, where they can be disabled or the order set
Framework Features Use a Good Trigger Framework
1. public void handle(SObjectType o) { // centralized trigger handler2. final String type = String.valueOf(o);3. if (!Boolean.valueOf(TriggerSettings.getInstance().EnableTriggers__c)) return;
4. try {5. if (!Boolean.valueOf(TriggerSettings.getInstance().get(‘Trigger_’ + type)) return;6. } catch (Exception ex) {} // if no setting exists, handlers are enabled by default7. 8. for (Handler__c h : handlers) {9. if (h.Active__c && h.Type__c.equalsIgnoreCase(type)) {10. final String handlerName = h.Name.trim();11. try {12. ITrigger t = (ITrigger)Type.forName(handlerName).newInstance();13. if (null != t) {14. execute(t);15. }16. } catch (NullPointerException ex) {}17. }18. }19. }
// Centralized dispatcher enforces disabling
Framework Features Use a Good Trigger Framework
1. private void execute(ITrigger handler) { // centralized trigger handler2. try {3. if (Trigger.isBefore) {4. if (Trigger.isInsert) {5. handler.bulkBeforeInsert(Trigger.newMap);6. for (SObject so : Trigger.new) {7. handler.beforeInsert(so);8. }9. } else if (Trigger.isUpdate) {10. handler.bulkBeforeUpdate(Trigger.oldMap, Trigger.newMap);11. for (SObject so : Trigger.old) {12. handler.beforeUpdate(so, Trigger.newMap.get(so.Id));13. }14. } else if (Trigger.isDelete) {15. handler.bulkBeforeDelete(Trigger.oldMap);16. for (SObject so : Trigger.old) {17. handler.beforeDelete(so);18. }19. }20. } else if (Trigger.isAfter) {21. . . .
// A common, logical ‘execute’ pattern provides consistent routing
Framework Features Use a Good Trigger Framework
1. public virtual class BaseHandler extends BaseClass implements ITrigger {2. /** the records that will be inserted when "andFinally" is called */3. protected SObject[] toInsert = new SObject[]{};4. . . .5. 6. /** handle bulk "before" processing of insert */7. public virtual void bulkBeforeInsert(Map<Id,SObject> sos)8. { Utils.preCondition(Test.isRunningTest() || (Trigger.isBefore && Trigger.isInsert)); }9. 10. /** handle bulk "before" processing of update */11. public virtual void bulkBeforeUpdate(Map<Id,SObject> oldSos, Map<Id,SObject> sos)12. . . .
13. /** insert, update, and delete the processed records */14. public virtual void andFinally() {15. Utils.preCondition(isValid());16. 17. insert toInsert;18. . . .
// Base classes make handler writing a snap
Conclusion
1. Avoid them if possible!
2. Only do DML when absolutely necessary
3. Test thoroughly
4. Use a good trigger framework
Writing bulletproof trigger code is challenging Summary
Sample frameworks and additional guidance Additional Resources
• Trigger Frameworks and Apex Trigger Best Practices – Kevin O’Hara
• An architecture framework to handle triggers in the Force.com platform – Hari Krishnan
• Trigger Pattern for Tidy, Streamlined, Bulkified Triggers – Tony Scott
• Advanced Apex Programming – Dan Appleman
Share Your Feedback, and Win a GoPro!
3 Earn a GoPro prize entry for each completed survey
Tap the bell to take a survey 2Enroll in a session 1