+ Start a Discussion
SF Beginner 2019SF Beginner 2019 

How to simplify this method to avoid cpu limit when bulk loading

public static void removeold(Set<Id> oldRecords){

    try{       
       ShareListoAgent = New List<SObject> ();
        ObjectName=new List<Id>(oldRecords).get(0).getSObjectType().getDescribe().getName();
        String queryStr ='select id,UserOrGroupId,parentid,RowCause  from';
        
        if(ObjectName == MemberUpper){
            queryStr = queryStr + ' MemberUpper_Share ';
        }
        if(ObjectName == MemberLower){
            queryStr = queryStr + ' MemberLower_Share ';
        }
        if(ObjectName == 'Account'){
            queryStr = 'select id,UserOrGroupId,AccountId,RowCause  from' + ' AccountShare where AccountId in:oldRecords and RowCause = \'Manual\'';
        }
        if(ObjectName == MemberLower || ObjectName == MemberUpper){
            queryStr = queryStr+'where ParentId in:oldRecords and RowCause = \'Manual\'';
        }
        ShareListoAgent.addAll(Database.query(queryStr));
        //ShareListoAgent = [select id,UserOrGroupId,parentid,RowCause  from MemberUpper_Share where parentid in: oldRecords and RowCause = 'Manual' ];
        system.debug('*******ShareListoAgent*******'+ShareListoAgent);
        if(ShareListoAgent !=null && ShareListoAgent.size()>0){
            delete ShareListoAgent;
        }
      }

 
Dhanasekar KDhanasekar K
Hi,

I am newbie to salesforce. Please bare me if the below suggestion does'nt helps you.,

1) Avoid multiple If condition inside block (Use else if)
2) Filter with more number of condition before fetching the record in object

Cheers !!!
Pradeep LandgePradeep Landge
Try if...else if... or switch statement:
public static void removeold(Set<Id> oldRecords){

    try{       
       ShareListoAgent = New List<SObject> ();
        ObjectName=new List<Id>(oldRecords).get(0).getSObjectType().getDescribe().getName();
        String queryStr ='select id,UserOrGroupId,parentid,RowCause  from';
        
        if(ObjectName == MemberUpper){
            queryStr = queryStr + ' MemberUpper_Share ';
        }else if(ObjectName == MemberLower){
            queryStr = queryStr + ' MemberLower_Share ';
        }else if(ObjectName == 'Account'){
            queryStr = 'select id,UserOrGroupId,AccountId,RowCause  from' + ' AccountShare where AccountId in:oldRecords and RowCause = \'Manual\'';
        }else if(ObjectName == MemberLower || ObjectName == MemberUpper){
            queryStr = queryStr+'where ParentId in:oldRecords and RowCause = \'Manual\'';
        }
        ShareListoAgent.addAll(Database.query(queryStr));
        //ShareListoAgent = [select id,UserOrGroupId,parentid,RowCause  from MemberUpper_Share where parentid in: oldRecords and RowCause = 'Manual' ];
        system.debug('*******ShareListoAgent*******'+ShareListoAgent);
        if(ShareListoAgent !=null && ShareListoAgent.size()>0){
            delete ShareListoAgent;
        }
      }