What are the best practices for Triggers

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


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