0% found this document useful (0 votes)
68 views7 pages

Salesforce Apex Trigger Interview Questions

This document outlines key interview questions and answers for Salesforce developers regarding Apex triggers and classes. It covers the differences between triggers and classes, the order of execution, types of triggers, handling bulk operations, preventing recursion, and best practices for writing efficient and maintainable triggers. Additionally, it emphasizes the importance of unit testing and adhering to Salesforce governor limits.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views7 pages

Salesforce Apex Trigger Interview Questions

This document outlines key interview questions and answers for Salesforce developers regarding Apex triggers and classes. It covers the differences between triggers and classes, the order of execution, types of triggers, handling bulk operations, preventing recursion, and best practices for writing efficient and maintainable triggers. Additionally, it emphasizes the importance of unit testing and adhering to Salesforce governor limits.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Ankita

Apex Trigger and Class Implementation: Interview


Questions for Salesforce Developers

1. What is the difference between a Trigger and an Apex Class in Salesforce?

Answer:

• Trigger: A trigger is a piece of Apex code that is executed before or after a record is
inserted, updated, deleted, or undeleted in Salesforce. It’s directly tied to a database
operation (DML operation) and helps automate actions such as validation, data
updates, or sending notifications.
• Apex Class: An Apex class is a reusable container of code that contains methods for
processing logic, performing operations, and interacting with Salesforce data. Classes
can be used in triggers, Visualforce pages, or Lightning components to implement
more complex logic.

2. Explain the order of execution in Salesforce when a record is inserted,


updated, or deleted. How do triggers fit into this?

Answer:
The order of execution is as follows when a record is inserted, updated, or deleted:

1. Validation Rules are executed.


2. Before Triggers fire (e.g., before insert or before update).
3. Duplicate Rules are checked.
4. Save to the database (records are saved).
5. After Triggers fire (e.g., after insert or after update).
6. Workflow Rules, Process Builder, or Flows are triggered.
7. Assignment Rules and Auto-response Rules are triggered.
8. Roll-up Summary Fields are updated.
9. Post-commit logic like sending emails, or executing outbound messages.

Triggers fit into the order by executing before or after the database operation.

3. What are the different types of triggers in Salesforce, and when should each
type be used?

Answer:

• Before Insert: Executes before the record is saved to the database. Useful for
validation or modifying the record before it's committed.
• After Insert: Executes after the record is saved. Good for operations that require the
record ID, such as sending notifications.
• Before Update: Executes before the record is updated in the database. It can be used
to modify the record before it’s saved.
• After Update: Executes after the record is updated. Can be used to update related
records or perform actions that need the latest data.

Joyful Learning
Ankita

• Before Delete: Executes before the record is deleted from the database. Can be used
to check for conditions before deletion.
• After Delete: Executes after the record is deleted. This is often used to clean up
related data or update other records.

4. How would you handle bulk operations in a trigger to avoid hitting


governor limits?

Answer:
To handle bulk operations, always use bulkified code in triggers:

• Use collections (lists, sets, maps) to store records and reduce the number of DML
operations.
• Process records in batches using for loops and minimize the number of DML
statements by performing them once for all records, rather than individually.
• Use [Link] and [Link] to handle large volumes of data efficiently.
• Avoid performing DML operations inside loops, as this can lead to hitting governor
limits.

5. What is the purpose of the [Link] and [Link] context variables in


Apex triggers?

Answer:

• [Link]: Contains the new versions of the records that are being inserted or
updated in the current transaction.
• [Link]: Contains the previous versions of the records that are being updated or
deleted. This is useful for comparing changes in fields when the record is updated or
deleted.

[Link] is available in before and after insert/update triggers, while [Link] is


available in after update and delete triggers.

6. How do you prevent recursive trigger calls?

Answer:
To prevent recursion, you can use a static variable. The static variable can store the state of
whether a trigger has been executed or not. For example:

apex
public class TriggerHandler {
public static Boolean isTriggerExecuted = false;
}

trigger AccountTrigger on Account (after update) {


if (![Link]) {
[Link] = true;
// your trigger logic here

Joyful Learning
Ankita

}
}

This ensures that the trigger runs only once per transaction.

7. What is the difference between before and after triggers?

Answer:

• before Trigger: Executes before the record is saved to the database. You can modify
the record in before triggers (e.g., modify field values, set default values).
• after Trigger: Executes after the record has been saved to the database. It is used
when you need to perform operations that require the record’s ID (e.g., updating
related records, sending notifications).

8. What are governor limits in Salesforce, and how do they impact Apex
triggers?

Answer:
Governor limits are restrictions that Salesforce places on the amount of resources you can
consume during a transaction to ensure multi-tenant architecture. Some common limits that
affect triggers include:

• Total number of SOQL queries: 100 per transaction.


• Total number of DML statements: 150 per transaction.
• Total heap size: 6 MB for synchronous transactions.
• Total number of records processed: 10,000 for DML operations.

To avoid hitting governor limits, use bulkified code, limit the number of SOQL queries, and
minimize DML operations inside loops.

9. Can you explain how you would handle DML operations within a trigger?

Answer:
To handle DML operations within a trigger:

• Bulkify your code: Perform DML operations outside loops to avoid hitting governor
limits.
• Use collections like lists, sets, or maps to store records and execute a single DML
operation for all records.

apex
List<Account> accountsToUpdate = new List<Account>();

Joyful Learning
Ankita

for (Account acc : [Link]) {


[Link] = [Link] + ' Updated';
[Link](acc);
}
update accountsToUpdate; // DML outside loop

10. What are [Link], [Link], and [Link], and


how are they useful in a trigger?

Answer:
These are Boolean context variables used to determine the type of trigger operation:

• [Link]: Returns true if the trigger is fired due to an insert operation.


• [Link]: Returns true if the trigger is fired due to an update operation.
• [Link]: Returns true if the trigger is fired due to a delete operation.

These are useful to conditionally handle logic based on the operation type.

11. What is a trigger handler, and why is it recommended to use one?

Answer:
A trigger handler is a class used to encapsulate trigger logic. It separates the trigger logic
from the trigger itself, making it cleaner, modular, and easier to maintain. It also facilitates
unit testing and makes it easier to follow best practices like bulk processing and recursion
prevention.

Example:

apex
public class AccountTriggerHandler {
public static void handleAfterInsert(List<Account> newAccounts) {
// Logic here
}
}

trigger AccountTrigger on Account (after insert) {


[Link]([Link]);
}

12. How do you handle errors in Apex triggers?

Answer:
Errors in triggers can be handled using try-catch blocks. For example:

apex
try {
// trigger logic here
} catch (Exception e) {
// Log the error or send an email notification
[Link]('Error: ' + [Link]());

Joyful Learning
Ankita

// Optionally, add an error to a record to prevent it from being saved


[Link][0].addError('Error occurred while processing the record.');
}

13. How would you write a trigger to prevent a record from being inserted if
certain conditions are not met?

Answer:
In a before insert trigger, you can add custom validation logic and prevent the insert by
adding an error to the record:

apex
trigger AccountTrigger on Account (before insert) {
for (Account acc : [Link]) {
if ([Link]([Link])) {
[Link]('Account name cannot be empty');
}
}
}

14. Can you explain what a "bulkified" trigger is and why it is important?

Answer:
A bulkified trigger is one that is designed to efficiently handle large numbers of records
(more than one). Bulkification ensures that the trigger can handle multiple records without
exceeding governor limits by using collections (lists, maps, sets) and processing records in
batches, rather than performing operations on each record individually.

For example, performing DML operations outside loops:

apex
Copy
List<Account> accountsToUpdate = new List<Account>();
for (Account acc : [Link]) {
[Link](acc);
}
update accountsToUpdate; // DML operation outside loop

15. How do you perform unit testing for Apex triggers?

Answer:
Unit tests for triggers should verify that the trigger logic works as expected. A unit test
should:

Joyful Learning
Ankita

• Create test data.


• Perform DML operations to trigger the trigger.
• Assert the expected changes to the records.

Example:

apex
@isTest
private class AccountTriggerTest {
@isTest static void testAccountInsert() {
Account acc = new Account(Name = 'Test Account');
insert acc;

// Assert expected outcome


Account insertedAcc = [SELECT Name FROM Account WHERE Id =
:[Link]];
[Link]('Test Account', [Link]);
}
}

This test creates a test account, inserts it, and then asserts that the trigger logic works
correctly.

16. Best Practice Question: How do you ensure that your Apex triggers follow
best practices and are scalable?

Answer:
To ensure that Apex triggers follow best practices and are scalable, the following principles
should be adhered to:

1. Bulkification: Always write bulkified triggers to handle multiple records efficiently.


This prevents hitting governor limits when processing large datasets.
o Example: Instead of using DML operations inside loops, collect records in
lists, and execute DML operations once for the entire list.

apex
Copy
List<Account> accountsToUpdate = new List<Account>();
for (Account acc : [Link]) {
[Link] = [Link] + ' Updated';
[Link](acc);
}
update accountsToUpdate; // Perform DML outside the loop

2. One Trigger Per Object: Salesforce allows only one trigger per object per event
(insert, update, delete). Make sure to follow the “single trigger” pattern by
centralizing your logic in one trigger. This helps in maintaining your code and avoids
duplicate processing.
3. Use Trigger Handlers: Use trigger handler classes to separate logic from the trigger
itself. This promotes code reusability, clarity, and easier unit testing. By using

Joyful Learning
Ankita

handlers, you can encapsulate logic into manageable chunks, making it easier to
maintain and extend.

apex
public class AccountTriggerHandler {
public static void handleAfterInsert(List<Account> newAccounts) {
// Trigger logic for after insert
}
}

trigger AccountTrigger on Account (after insert) {


[Link]([Link]);
}

4. Limit SOQL and DML Statements: Avoid excessive SOQL queries or DML
operations within loops. Ensure that your trigger is optimized to avoid hitting
governor limits, especially when handling large data volumes. Use maps or sets to
optimize lookups and reduce the number of queries.
5. Minimize Hard-Coded Values: Avoid hardcoding values in your triggers. Instead,
use custom settings or custom metadata types for configurations and business rules to
ensure flexibility and ease of maintenance.
6. Handle Recursive Trigger Calls: Use static variables to prevent recursive calls from
a trigger. Recursive trigger calls can occur when a trigger causes updates to the same
object that fires the trigger again, leading to infinite loops or hitting governor limits.

apex
public class TriggerHandler {
public static Boolean isTriggerExecuted = false;
}

trigger AccountTrigger on Account (after update) {


if (![Link]) {
[Link] = true;
// Trigger logic
}
}

7. Test Coverage: Always write comprehensive unit tests for triggers, covering positive
and negative scenarios. This ensures that the trigger works as expected and also helps
in maintaining high test coverage for deployment.

By following these best practices, you ensure that your triggers are optimized, maintainable,
and efficient, capable of handling larger data volumes while adhering to Salesforce’s
governor limits.

Joyful Learning

You might also like