How to write Apex Triggers like a Professional?

Apex Triggers are used to make custom actions before or after a database event.

When should you prefer Triggers over Flows?

You should choose Triggers over Flows when:

  1. Performance and Scale are important.
  2. Logic is too complex for point-and-click tools.
  3. Executing CPU-intensive operations.

Trigger Syntax

You can use the below framework while creating a trigger for any object. It separates the action on the basis of different operations.

trigger triggerName on objectName(before insert, after insert, before update, after update, before delete, after delete, after undelete){
    if(Trigger.isBefore && Trigger.isInsert){
        // Perform Action
    }
    if(Trigger.isAfter && Trigger.isInsert){
        // Perform Action
    }
    if(Trigger.isBefore && Trigger.isUpdate){
        // Perform Action
    }
    if(Trigger.isAfter && Trigger.isUpdate){
        // Perform Action
    }
    if(Trigger.isBefore && Trigger.isDelete){
        // Perform Action
    }
    if(Trigger.isAfter && Trigger.isDelete){
        // Perform Action
    }
    if(Trigger.isAfter && Trigger.isUndelete){
        // Perform Action
    }
}

We have the following context variables available in a Trigger:

  1. Trigger.isExecuting
  2. Trigger.isBefore
  3. Trigger.isAfter
  4. Trigger.isInsert
  5. Trigger.isUpdate
  6. Trigger.isDelete
  7. Trigger.isUndelete
  8. Trigger.New
  9. Trigger.Old
  10. Trigger.newMap
  11. Trigger.oldMap
  12. Trigger.OperationType
  13. Trigger.size

How to choose between Before and After Trigger?

Before triggers are used to update or validate record values before they’re saved to the database. So you should use Before Triggers to update the Triggering Record.

After triggers are used to access field values that are set by the system (such as a record’s Id or LastModifiedDate field) and to affect changes in other records. The records that fire the after trigger are read-only.

 But that does not mean you can not create other records in the before trigger. 

For Example: If you want to Create an Account whenever a new Contact is Inserted and the AccountId of the Contact should have the Account Id. In this case, you should use the Before Trigger on the Contact Object.

How to Validate records in a Before Trigger?

We use the addError() method to stop any record from getting inserted into the database.

Best Practices to follow while creating a Trigger

You should follow the following best practices while creating a Trigger:

1) Create Only ONE Trigger per object.
2) Logic – Less Trigger. Keep the Logic part in the Trigger Handler.
3) Context-Specific Handler Methods
4) Bulkify your Code
5) Avoid SOQL Queries or DML statements inside FOR Loops
6) Avoid Hardcoding IDs