I have to implement same logic x=y+z for after insert and after update trigger on an object. Unfortunately I cannot make use of context variables as our prototype for trigger handler is defined long ago and they have not taken these into considerations. So I am planning to implement the logic in a method in the below way. Please let me know if this is the correct way or suggest if there is any better way of doing this.

public void Samelogic(Map<..> oldMap, Map<..> newMap){
  //Local variable flag
  boolean flag = 0;
  //After Insert
    if(condition1){ flag =1;}
  //After update
    if(conditon2){ flag =1;}

  if(flag ==1){
    //Perform common logic

Your code won't work as you expect: oldMap is null in an insert trigger, and will crash with a NullPointerException. You might want to just go with a switch statement:

Boolean doAction = false;
switch on Trigger.operationType {
    doAction = condition1;
    doAction = condition2;
if(doAction) {
  x = y + z;

Trigger context variables are available in classes, so long as you're actually in a trigger context (between a DML_BEGIN and a DML_END). And the if statements are not always necessary; you can always assign the result of using Boolean operators to a Boolean variable.

  • Thanks for the solution. Just checking with you again, it means that i need not to explicitly pass this Trigger.operationType from trigger handler?
    – Kanikala
    Sep 14 '18 at 3:22
  • @Kanikala correct. If you're using a framework of any sort, and you don't know why you're doing it this way, you need to do some research and/or ask more questions.
    – sfdcfox
    Sep 14 '18 at 3:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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