Tag Archives: Apex Trigger

Apex Trigger Best Practices

One Trigger Per Object: A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts.

Logic-less Triggers: Avoid complex logic in triggers. To simplify testing and re-use, triggers should delegate to Apex classes which contain the actual execution logic.

Context-Specific Handler Methods: Create context-specific handler methods in Trigger handlers.

Bulkify your Code: Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

Avoid SOQL Queries or DML Statements inside FOR Loops: An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception.

Using Collections, Streamlining Queries, and Efficient For Loops: It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits.

Querying Large Data Sets: The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore.

Use @future Appropriately: It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found.

Avoid Hardcoding IDs: When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail.

Consistent Naming Convention: Use a consistent naming convention including the object name (e.g. AccountTrigger).

Test Class For Apex Trigger

Here in below example the apex trigger is on “Account” object, to check duplicate Account Names.

Apex Trigger:

trigger AccountTrigger on Account (before Insert, before Update) {
     
    Map<String, Account> accMap = new Map<String, Account>();
     
    for (Account acc : System.Trigger.new) {
         
        //Make sure you don't treat account Name that isn't changing during an update as a duplicate.  
        if (System.Trigger.isInsert || (acc.Name != System.Trigger.oldMap.get(acc.Id).Name)) {
             
            //Make sure another new account isn't also a duplicate  
            if (accMap.containsKey(acc.Name)) {
                acc.Name.addError('An account already exist with same name.');
            } else {
                accMap.put(acc.Name, acc);
            }
        }
    }
     
    //Query to find all the Accounts in the database that have the same name as any of the Accounts being inserted or updated.  
    for (Account acc : [SELECT Name FROM Account
                        WHERE Name IN :accMap.KeySet()]) {
                            Account newAcc = accMap.get(acc.Name);
                            newAcc.Name.addError('An account already exist with same name.');
                        }
}

Here is the Test Class for the above apex trigger.
Test Class:

@isTest
private class TestAccountTriggers {

    static testMethod void AccountTriggerUnitTest() {
	
        Account acc1 = new Account();
        acc1.Name = 'ABC Corp Ltd';
        acc1.Type = 'Prospect';
        acc1.Industry = 'Banking';
        Insert acc1;
		
        Account acc2 = new Account();
        acc2.Name = 'ABC Corp Ltd';
        acc2.Type = 'Prospect';
        acc2.Industry = 'Apparel';
		
        try
        {
        	Insert acc2;
        }
        catch(System.DMLException e)
        {
        	System.assert(e.getMessage().contains('An account already exist with same name.'));
        }
    }
}