3

I ran the following code in anonymous apex:

System.debug('Value of Trigger.isBefore: ' + Trigger.isBefore);
if (Trigger.isBefore) { System.debug('In is before trigger.'); }

Line 1 prints:

"Value of Trigger.isBefore: null"

Line 2 throws a NPE:

System.NullPointerException: Attempt to de-reference a null object

I am curious as to why Line 1 is not throwing the exception if there's one caused by Trigger.isBefore?

I modified the if statement from line 2 like so:

if (Trigger.isBefore == true) { System.debug('In is before trigger.'); }

Now the above if statement no longer throws a NPE. Does anybody know why I am witnessing this behavior?

1 Answer 1

4

In all contexts, Trigger itself always exists. However, when Trigger.isExecuting is false, all other context variables are null. It's acceptable to String.valueOf a null value (it outputs null). However, you can't have a null condition when a Boolean condition is expected, for example, while or if.

Consider the following code:

Boolean flag;
System.debug(''+flag); // "null"
System.debug(String.valueOf(flag)); // also "null"
if(flag) {
  System.debug('Flag is true');
}

This code will also throw a NullPointerException on the if statement, because flag is null, even though the debug statement works just fine.

When you add the equality operator to compare null to true:

Boolean flag;
System.debug(''+flag); // "null"
System.debug(String.valueOf(flag)); // also "null"
if(flag == true) {
  System.debug('Flag is true');
}

You get the comparison result of false, and no NullPointerException is thrown.

1
  • Excellent response, that makes sense now!
    – Arthlete
    Apr 14, 2023 at 19:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .