Looking to boost your Apex development skills with practical, clever approaches? Here are some tricky and lesser-known Apex code techniques that Salesforce developers can use to simplify daily tasks, make code more efficient, and avoid common pitfalls.
Build flexible queries at runtime without risking SOQL injection.
public static List<sObject> getRecords(String objName, String filterField, String filterValue) {
String query = 'SELECT Id, Name FROM ' + String.escapeSingleQuotes(objName) +
' WHERE ' + String.escapeSingleQuotes(filterField) + ' = :filterValue';
return Database.query(query);
}
Tip: Always validate and sanitize input to avoid SOQL injection.
Quickly group records by a field for efficient lookups.
Map<Id, List<Contact>> contactsByAccount = new Map<Id, List<Contact>>();
for(Contact c : [SELECT Id, AccountId FROM Contact WHERE AccountId != null]) {
if(!contactsByAccount.containsKey(c.AccountId)) {
contactsByAccount.put(c.AccountId, new List<Contact>());
}
contactsByAccount.get(c.AccountId).add(c);
}
Use case: When you need to process related records in bulk.
Assign defaults using ternary operator to handle nulls elegantly.
String region = user.Region__c != null ? user.Region__c : 'Default Region';
Use external IDs for seamless insert/update.
upsert myContacts Contact_External_ID__c;
Benefit: No need to check if the record exists—Apex handles it.
Leverage Comparable interface for custom sorting.
public class MyObj implements Comparable {
public String name;
public Integer priority;
public Integer compareTo(Object o) {
MyObj other = (MyObj) o;
return this.priority - other.priority;
}
}
List<MyObj> objs = new List<MyObj>();
// add objs...
objs.sort();
Update a specific field across multiple records in one line.
for(Account acc : accList) acc.Status__c = 'Active';
update accList;
Access fields without hardcoding names.
String fieldName = 'Custom_Field__c';
for(SObject s : records) {
s.put(fieldName, 'Value');
}
Only update/insert when there are records.
if(!accList.isEmpty()) update accList;
Remove duplicates from a list with a Set.
List<String> emails = new List<String>{'a@example.com', 'b@example.com', 'a@example.com'};
Set<String> uniqueEmails = new Set<String>(emails);
emails = new List<String>(uniqueEmails);
Catch exceptions and provide meaningful error details.
try {
// risky logic
} catch(Exception ex) {
System.debug('Error: ' + ex.getMessage());
throw new CustomException('Failed due to: ' + ex.getMessage());
}
Happy Coding!
Use these tricks to write cleaner, safer, and more efficient Apex code every day!
Post a Comment