As we know that salesforce keeps updating 3 times a year. With these releases, Salesforce introduces many new features in the apex code also. Earlier I was using the following approach when writing a trigger on any object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
trigger AccountTrigger on Account (before insert, after insert, before update, after update, before delete, after delete, after undelete) { if(Trigger.isBefore && Trigger.isInsert) { // Before Insert } if(Trigger.isAfter && Trigger.isInsert) { // After Insert } if(Trigger.isBefore && Trigger.isUpdate) { // Before Update } if(Trigger.isAfter && Trigger.isUpdate) { // After Update } if(Trigger.isBefore && Trigger.isDelete) { // Before Delete } if(Trigger.isAfter && Trigger.isDelete) { // After Delete } if(Trigger.isAfter && Trigger.isUndelete){ // After Undelete } } |
But after getting Switch When and Trigger.operationType, I decided to use the below design for writing the trigger logic. This is more readable and looks more clear.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
trigger AccountTrigger on Account (before insert, after insert, before update, after update, before delete, after delete, after undelete) { switch on Trigger.operationType { when BEFORE_INSERT { // Before Insert } when AFTER_INSERT { // After Insert } when BEFORE_UPDATE { // Before Update } when AFTER_UPDATE { // After Update } when BEFORE_DELETE { // Before Delete } when AFTER_DELETE { // After Delete } when AFTER_UNDELETE { // After Undelete } } } |