I have a general question about comparing newMap
values with oldMap
values in an Apex Class made for both update and insert contexts.
Let's say we have an Account Handler method that must run when an Account Name is changed or the Account is created.
When testing the below code for an update context everything will work fine since we're able to compare Trigger.oldMap
with Trigger.newMap
.
public class exampleAccountHandler {
public static void exampleAccountMethod (Map<Id, Account> accountListNew, Map<Id, Account> accountListOld) {
// Code
for (Account myAccount : accountListNew.values()) {
if (accountListNew.get(myAccount.Id).Name != accountListOld.get(myAccount.Id).Name) {
// Logic
}
}
}
}
In the Account Master Trigger it will look somewhat like this:
if (Trigger.isBefore)
if (Trigger.isUpdate) {
exampleAccountHandler.exampleAccountMethod(Trigger.oldMap, Trigger.newMap);
}
When we're testing the same for an insert context it will throw a null pointer exception error since we don't have anything to compare on the oldMap side (it will run the if clause where the oldMap
is referenced). Also, Trigger.oldMap
cannot be used in the insert context.
What are the best practices to circumvent this issue? Define a separate method for the insert context (I assume there can only be Trigger.newMap
as an input)? Adding logic to the Trigger (I guess no)? Something in between?
Looking forward to your help!
Account oldAccount = accountListOld.get(myAccount.Id) == null ? new Account() : accountListOld.get(myAccount.Id)
.