Optimize Your Salesforce Code: 10 Apex Issues and Proven Solutions

Introduction

Apex is a powerful programming language used in Salesforce development. However, like any programming language, it has its own set of challenges and pitfalls. In this blog post, we will explore 30 common Apex development issues and provide code examples along with their solutions to help you write efficient, optimized, and scalable Apex code.

① SOQL Queries in Loops

⚠️ Issue: Executing SOQL queries within loops can quickly consume governor limits and impact performance.

Example:

List<Account> accounts = [SELECT Id, Name FROM Account];
for (Account acc : accounts) {
List<Contact> contacts = [SELECT Id, Name FROM Contact WHERE AccountId = :acc.Id];
// Perform some operation on contacts
}
view raw soqlExample.cls hosted with ❤ by GitHub

Solution: Use a single query to retrieve all the required data and leverage relationships or collections to access the related records.

List<Account> accounts = [SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account];
for (Account acc : accounts) {
List<Contact> contacts = acc.Contacts;
// Perform some operation on contacts
}
view raw SOQLIssueSol.cl hosted with ❤ by GitHub

② Large DML Operations

⚠️ Issue: Performing DML (Data Manipulation Language) operations in bulk without proper handling can lead to governor limit exceptions.

Example:

List<Account> accountsToUpdate = [SELECT Id, Name FROM Account];
for (Account acc : accountsToUpdate) {
acc.Name = 'Updated Name';
}
update accountsToUpdate;

Solution: Use a single query to retrieve all the required data and leverage relationships or collections to access the related records.

③ Null Pointer Exceptions

⚠️ Issue: Uninitialized variables or unchecked null values can cause Null Pointer Exceptions.

Example:

String name;
System.debug('Name: ' + name);

Solution: Initialize variables with default values or check for null values before accessing them.

String name = '';
if (name != null) {
System.debug('Name: ' + name);
}
view raw nullCheck.cls hosted with ❤ by GitHub

④ Querying Large Data Sets

⚠️ Issue: Querying large data sets without proper optimization can result in performance issues

Example:

List<Account> accounts = [SELECT Id, Name FROM Account];

Solution: Use query optimization techniques like selective filtering, indexing, and limiting the number of returned records.

List<Account> accounts = [SELECT Id, Name FROM Account WHERE CreatedDate = LAST_N_DAYS:7 LIMIT 1000];
view raw soqlFilter.cls hosted with ❤ by GitHub

⑤ Unhandled Exceptions


⚠️ Issue: Not handling exceptions properly can result in unexpected behavior or system failures.

Example:

try {
// Code that may throw an exception
} catch (Exception e) {
// Exception handling
}

Solution: Implement appropriate exception handling mechanisms to catch and handle exceptions gracefully.

try {
// Code that may throw an exception
} catch (Exception e) {
System.debug('An error occurred: ' + e.getMessage());
}

⑥ Governor Limit Exceedance


⚠️ Issue: Apex has various governor limits, and exceeding them can cause runtime exceptions or failures

Example: In synchronous apex a query can return only 50K records.

List<Account> accounts = [SELECT Id, Name FROM Account];
System.debug('Total accounts: ' + accounts.size());
view raw soqlLimit.cls hosted with ❤ by GitHub

Solution: Monitor and analyze the governor limits using system methods like Limits.getQueries() and optimize code accordingly.

⑦ Inefficient Code Logic


⚠️ Issue: Inefficient code logic can lead to performance bottlenecks and suboptimal execution

Example:

List<Contact> contacts = [SELECT Id, Name FROM Contact];
for (Contact con : contacts) {
if (con.Account.Name == 'Some Account') {
// Perform some operation
}
}

Solution: Refactor the code logic to reduce unnecessary iterations or avoid complex operations within loops.

Set<Id> accountIds = new Set<Id>();
for (Contact con : [SELECT Id, Name, AccountId FROM Contact WHERE Account.Name = 'Some Account']) {
accountIds.add(con.AccountId);
}

⑧ Incomplete or Incorrect Data Validation


⚠️ Issue: Lack of proper data validation can lead to data integrity issues or unexpected behaviors.

Example:

public void updateAccount(Account acc) {
if (acc.Name != null) {
update acc;
}
}

Solution: Implement comprehensive data validation checks to ensure data consistency and integrity.

public void updateAccount(Account acc) {
if (acc.Name != null && acc.Name != '') {
update acc;
}
}

⑨ Long-Running Processes


⚠️ Issue: Long-running processes can impact system performance and cause timeouts or delays

Example:

public void performLongRunningOperation() {
    // Perform a complex and time-consuming task
}

Solution: Break down long-running processes into smaller, manageable tasks and leverage asynchronous processing, such as queueable Apex or batch Apex.

⑨ Data Skew

⚠️ Issue: Data skew occurs when records are unevenly distributed across a lookup or master-detail relationship, leading to performance degradation and locking issues.

Example:

List<Contact> contacts = [SELECT Id, Name FROM Contact WHERE AccountId = :accountId];

Solution: Implement data skew mitigation techniques such as using a custom indexing strategy or introducing a helper object to distribute the records evenly.

①⓪ Inefficient Use of Collections

⚠️ Issue : Inefficient use of collections, such as lists or sets, can result in unnecessary iterations or duplicate entries.

Examples:

Set<String> uniqueNames = new Set<String>();
List<String> names = new List<String>{'John', 'Jane', 'John'};
for (String name : names) {
uniqueNames.add(name);
}
view raw collection.cls hosted with ❤ by GitHub

Solution: Utilize appropriate collection methods and constructors to remove duplicates or perform set operations directly.

Set<String> uniqueNames = new Set<String>(names);

Conclusion

In this blog post, we explored 10 common Apex development issues and their solutions. By addressing these issues and adopting best practices, you can write more efficient, scalable, and maintainable Apex code. Remember to analyze governor limits, optimize queries and loops, handle exceptions gracefully, and appropriate collection. With these techniques, you’ll be on your way to becoming a proficient Apex developer.

About the blog

SFDCLessons is a blog where you can find various Salesforce tutorials and tips that we have written to help beginners and experienced developers alike. we also share my experience and knowledge on Salesforce best practices, troubleshooting, and optimization. Don’t forget to follow us on:

Newsletter

Subscribe to our email newsletter to be notified when a new post is published.

Advertisements
Advertisements

Arun Kumar

Arun Kumar is a Salesforce Certified Platform Developer I with over 7+ years of experience working on the Salesforce platform. He specializes in developing custom applications, integrations, and reports to help customers streamline their business processes. Arun is passionate about helping businesses leverage the power of Salesforce to achieve their goals.

Leave a Reply