Salesforce has context variables like Trigger.IsInsert just to understand if trigger is running for Insert scenarios. However, we could always have got this information by doing the NULL check on Trigger.Old or Trigger.OldMap

Example:

We always use it in below scenarios:

Scenarios 1: if(Trigger.isInsert){ method1(); }

Scenarios 2: if(Trigger.old == null){ method1(); }

In both the scenarios, decision/control statements are same and have the same complexity. What's the benefit of having it then?

First of all, you get significantly clearer semantics when you check if (trigger.isInsert) rather than checking if (trigger.old == null). It also adds consistency and completeness with the isBefore and isAfter attributes, which you could not check by inspecting the collection values.

Second of all, checking for the presence of trigger.new and trigger.old does not suffice to uniquely check all operations. For example, both before insert and before undelete have trigger.old == null && trigger.new != null.

  • To add, if the conditions for inserting change, then having those qualities in a function means the end user doesn't have to change their code at all. – Carl Nov 15 at 3:36

There are more trigger events than just insert and update. Trigger.old is also available in delete triggers (see Trigger Context Variables), so comparing Trigger.old to null is not sufficient by itself to identify which trigger event we are running in. Likewise, Trigger.new is available (without Trigger.old) in both insert and undelete context.

Even if we could derive the trigger event by making various comparisons between Trigger.new, Trigger.old, and null, it's clearer and more semantically meaningful to just write

if (Trigger.isInsert) {

rather than

if (Trigger.new != null && Trigger.old == null) {

In fact, we now have Trigger.operationType to even further streamline this type of code with constructs like

switch on (Trigger.operationType) {
    when BEFORE_INSERT {
        // do stuff...
    }
    when AFTER_UPDATE {
        // ...
    }
    // ...
}
  • 1
    I was going to add in something about trigger.operationType but now that you have it here, I'll leave my answer as is. – Adrian Larson Nov 14 at 20:22

You can get Trigger.Old in Update and Delete context, so you cannot guarantee its insert just by adding a null check on Trigger.old.

Thats where isInsert ,isDelete,isUpdate,isUndelete comes in picture.

Trigger.old Returns a list of the old versions of the sObject records.
This sObject list is only available in update and delete triggers.

Source: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_context_variables.htm

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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