+ Start a Discussion
Neeraj Sharma 103Neeraj Sharma 103 

How to reduce line of codes or query reduce in trigger Please help me for below trigger to reduce line of codes

Hi Everyone how to reduce line of codes 
this logic i used many times in trigger and my code length is line 400 lines so how to reduce them only the UserRole.Name is changed according to hierarchy because my hierarchy is so long its for 6-7 states so i used this logic for all states only role name is changed in the query this below code part is only little






trigger Distributor on Account (before insert,before update) {
    
String role;
String owner;
    
  list<Account> changeOwner=new list<Account>();
    
    for(Account acc:trigger.new){
        
       if(acc.Under__c=='Chhattisgarh'){
           role='SO CG';
           changeOwner.add(acc);
       }
   list <User> socg1=[select id,Name from User where UserRole.Name='SO CG' Order BY FirstName,LastName];
   list <User> socg2=[select id,Name from User where UserRole.Name='ASM CG' Order BY FirstName,LastName];
   list <User> socg3=[select id,Name from User where UserRole.Name='DRM CG' Order BY FirstName,LastName];
   list <User> socg4=[select id,Name from User where UserRole.Name='RM CG' Order BY FirstName,LastName];
  
   if(socg1.size()>0){
        owner=socg1.get(0).id;
    }
    
     else if(socg1.size()<=0){
     
        if(socg2.size()>0){
            owner=socg2.get(0).id; 
        }
        
        else if(socg2.size()<=0){
            
            if(socg3.size()>0){
              owner=socg2.get(0).id;  
             }
        
        else if(socg3.size()<=0){
            
             if(socg4.size()>0) {
               owner=socg4.get(0).id;   
             }   
        }
      }
   }
   for(Account acc:changeOwner){
       
        if(socg1!=null){
            acc.OwnerId=Owner;
        }
    }
    
Best Answer chosen by Neeraj Sharma 103
Tad Aalgaard 3Tad Aalgaard 3
I'm having a hard time understanding what it is you wish to accomplish.  But if you want to reduce the number of lines you should combine your nested "if" statements.

Example
else if(socg3.size()<=0){
            
             if(socg4.size()>0) {
               owner=socg4.get(0).id;   
             }   
}

// change to the following

else if(socg3.size()<=0 && socg4.size()>0) {
               owner=socg4.get(0).id;   
}

If the reason you want to reduce the lines of code is because you're having a hard time getting a test class to cover everything then the above won't help (but should be followed) as you'll need to wrtie test methods with logic that satisfies the conditions of the if statements in your trigger.