[SalesForce] Prevent account from deleting, if it has 2 or more contacts

I am new to Salesforce Apex Development.I have written this code to avoid deletion of account if it has more than 2 contacts. I works fine but I am not sure if I have followed all the best practices.

Feel free to provide your feedback

public static void restrictDetail(List<Account> acclist){
        Set<Id> accset = new Set<id>();
        Integer numofcontacts =0;
        for(Account acc : acclist){
            accset.add(acc.id);
        }
       List<AggregateResult> aresult =[Select count(Id) cid from Contact where AccountId in :accset ];
        for( AggregateResult ar : aresult ){
            numofcontacts =(Integer) ar.get('cid');  
        }
        for(Account acc : acclist){
            if(numofcontacts >=2){
                acc.adderror('We cannot delete this');
            }
        }
    }

Best Answer

I believe this is written in beforeDelete, so you will always have your ID, Spo, instead of passing a List<Account> you can pass the Map<Id, Account> mapAccount from Trigger context.

That will escape one loop which you are doing to get the Ids from Account and you query will become:

List<AggregateResult> aresult =[Select count(Id) cid from Contact where AccountId in :mapAccount.keySet() ];

Related Topic