6

My requirements are:

  1. Upon creation of Accounts there is a trigger that creates a contact with specific record type Organization Donor Proxy
  2. I wanted to create another trigger on Account after Insert/Update that will update a field Aaron_Contact_id__c with the Aaron_Account_id__c

Trigger

trigger Account_UpdateDonorProxyTrigger on Account (after insert, after update) {

    Contact[] dpContact = new list<Contact>();        // donor proxy contact

    try{
        Map<id, account> acctMap = Trigger.newmap;
        //for (Account acct : trigger.new){
        System.debug('account ids >>> :' + acctMap.keyset());        
        // Get all the contacts against each AccountId
        for (Contact cnt: [SELECT contact.id, contact.accountid, contact.name, contact.Aaron_Contact_Id__c, contact.RecordType.Name
                           FROM Contact
                           WHERE Contact.accountid IN: acctMap.keyset() ]){ 
            System.debug('Contact record type <<< :' + cnt.RecordType.Name);
            if(cnt.RecordType.Name == 'Organization Donor Proxy'){

                cnt.Aaron_Contact_ID__c = acctMap.get(cnt.accountid).Aaron_Account_ID__c;
                dpContact.add(cnt);

            }
        }       // end of for loop
        //}            
        update dpContact;
    }
    catch (exception ex){
        System.Debug('stack trace string:::' + ex.getStackTraceString() );
    }

}

Question Does this trigger comply with the apex best practices? Am I missing something or anything that can be improved? What are the best practices and pitfalls in triggers anyways.

  • I realize this question has an accepted answer, but I thought I'd point out that you don't need a trigger. What you are trying to accomplish can be done with Process Builder. – dBeltowski May 10 '16 at 14:57
  • @DougB: True that but (a) this question was posted when Process builder was not out. (b) I, rather needed to know the whether my code is in compliance with the best practices. – Mahmood May 10 '16 at 15:03
11

After searching here and there and writing few triggers myself, I have come up with the following:

  1. Follow proper naming conventions to make your code more logical and readable.
  2. Write one-trigger per object.
    • Use trigger context-variables to identify specific event and performs tasks accordingly.
  3. Logic-less triggers
    • Now, debugging in apex is itself serious pain, adding whole lot of logic in trigger and debugging it is... well you can guess. So, break your trigger logic in to trigger-handler classes.
  4. Context-Specific Handler Methods
    • Using specific methods in your trigger-handler-class to keep your code clean and scalable.
  5. Use a framework.
    • A framework! Why? It will make your code conform to the best practices, better testing, scalability and cleaner.
  6. Keep the salesforce order-of-execution of events in mind (they will come in handy).
  7. Understand when to use before-trigger and when to user after-trigger.
  8. Write trigger logic to support bulk operations.
  9. Triggers can't contain test methods. So, its unit tests must be saved in a separate file.
  10. Use custom settings to turn the trigger On/Off.
    • Once deployed, any changes or making a trigger Active/Inactive, you would need to make the changes on sandbox and then push it from their using changeset or IDE. Using custom settings to make a decision on the trigger will make life easy.

Helpful links: https://developer.salesforce.com/page/Trigger_Frameworks_and_Apex_Trigger_Best_Practices http://www.iterativelogic.com/salesforce-apex-trigger-best-practices/ http://krishhari.wordpress.com/2013/07/22/an-architecture-framework-to-handle-triggers-in-the-force-com-platform

https://developer.salesforce.com/page/How_to_Write_Good_Unit_Tests https://developer.salesforce.com/blogs/developer-relations/2015/01/apex-best-practices-15-apex-commandments.html https://developer.salesforce.com/page/Trigger_Frameworks_and_Apex_Trigger_Best_Practices

2

If the trigger is working properly, then for the best practices

1) Never use a try-catch block to control logic flow. Always use some type of if-else construct. Exception handling is for dealing with problems, or things that you don't expect.

Source : [Apex TRY ... CATCH ... FINALLY Syntax

2) Instead of writing multiple Triggers on the same object, it is best practice to create one trigger and handle all the contexts in the Handler Classes.

http://developer.force.com/cookbook/recipe/trigger-pattern-for-tidy-streamlined-bulkified-triggers

  • +1 - I really like to second point. I guess I'm pretty much in-compliance with the first point :) – Mahmood Dec 9 '14 at 17:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.