Notes
When writing Apex code in Salesforce, efficiency and clarity are key. In this article, we'll explore a simple refactoring technique to improve the readability and performance of your code.
The Original Code
// ❌ This can be refactored
List<Id> accIds = new List<Id>();
for (Account a : Trigger.new) {
accIds.add(a.Id);
}
List<Account> accounts = [SELECT Id, Name,
(SELECT Id FROM Contacts)
FROM Account
WHERE Id IN :accIds];
System.debug('? ' + accounts);
The Problem
The code above iterates through each Account
in Trigger.new
, collects the Id
s, and then queries the Account
object based on these Id
s. While this works, it involves unnecessary steps:
- Creating a list
accIds
and manually adding each Account
Id.
- Using that list in the
SOQL
query to fetch the Account
records.
The Refactored Code
// ✅ Refactor to this
List<Account> accounts = [SELECT Id, Name,
(SELECT Id FROM Contacts)
FROM Account
WHERE Id IN :Trigger.new];
System.debug('? ' + accounts);
Why This Refactor Works
By directly referencing Trigger.new
in the WHERE
clause of the SOQL
query, you eliminate the need for an additional list and loop. Trigger.new
is already a collection of the Account
records being processed, so you can use it directly. This approach is not only more concise but also more efficient.
Key Takeaways
- Simplify Loops: Avoid unnecessary loops when you can leverage existing collections like
Trigger.new
.
- Direct Querying: Use
Trigger.new
directly in your SOQL
queries for better performance.
- Readability: Cleaner code is easier to read, maintain, and debug.
By applying these refactoring techniques, your Apex code will be more efficient and maintainable, leading to better performance in your Salesforce applications.
Video
Video does not exists.