Tricky Apex Logic to Boost Daily Productivity

 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.


1. Dynamic SOQL Query Construction

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.


2. Map Grouping With Apex Collections

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.


3. Null Coalescing for Default Values

Assign defaults using ternary operator to handle nulls elegantly.

String region = user.Region__c != null ? user.Region__c : 'Default Region';

4. Efficient Upserts to Avoid Duplicates

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.


5. Sorting Lists of Custom Objects

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();

6. Bulkified Field Updates

Update a specific field across multiple records in one line.

for(Account acc : accList) acc.Status__c = 'Active'; update accList;

7. Dynamic Field Access with SObject

Access fields without hardcoding names.

String fieldName = 'Custom_Field__c'; for(SObject s : records) { s.put(fieldName, 'Value'); }

8. Conditional DML to Avoid Errors

Only update/insert when there are records.

if(!accList.isEmpty()) update accList;

9. Using Sets for Fast Deduplication

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);

10. Exception Handling with Custom Messages

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!

0 Comments

Post a Comment

Post a Comment (0)

Previous Post Next Post