Apex is a powerful language used for development on the Salesforce platform. Here’s a concise yet comprehensive cheat sheet to help you master Apex coding.
Basics
Syntax:
- Apex is case-insensitive.
- Statements end with a semicolon (
;
).
Variables:
Integer count = 10; String name = 'Salesforce'; Boolean isActive = true;
Comments:
// Single-line comment /* Multi-line comment */
Data Types
- Primitive Types:
Integer
,Double
,Long
,Date
,Datetime
,String
,ID
,Boolean
- sObject Types: Any Salesforce object (e.g.,
Account
,Contact
) - Collection Types:
List
,Set
,Map
- Custom Types: User-defined classes, enums, interfaces
Collections
List:
List<String> names = new List<String>{'Alice', 'Bob', 'Charlie'}; names.add('Diana');
Set:
Set<Integer> ids = new Set<Integer>{1, 2, 3}; ids.add(4);
Map:
Map<Id, Account> accounts = new Map<Id, Account>{}; accounts.put(acc.Id, acc);
Control Flow
If-Else:
if (condition) { // code } else if (condition) { // code } else { // code }
For Loop:
for (Integer i = 0; i < 10; i++) { // code } for (Account acc : [SELECT Id, Name FROM Account]) { // code }
While Loop:
while (condition) { // code }
DML Operations
Insert:
Account acc = new Account(Name='Acme Inc'); insert acc;
Update:
acc.Name = 'Acme Corporation'; update acc;
Delete:
delete acc;
Upsert:
upsert acc;
SOQL (Salesforce Object Query Language)
Basic Query:
List<Account> accounts = [SELECT Id, Name FROM Account];
Where Clause:
List<Contact> contacts = [SELECT Id, Name FROM Contact WHERE AccountId = :accId];
Order By:
List<Account> sortedAccounts = [SELECT Id, Name FROM Account ORDER BY Name ASC];
Aggregate Functions:
AggregateResult[] results = [SELECT COUNT(Id) total FROM Account]; Integer totalAccounts = (Integer)results[0].get('total');
SOSL (Salesforce Object Search Language)
List<List<SObject>> searchResults = [FIND 'Acme' IN ALL FIELDS RETURNING Account(Id, Name), Contact(Id, Name)];
Exception Handling
try { // code that might throw an exception } catch (DmlException e) { // handle the exception } finally { // code that runs regardless of whether an exception was thrown }
Apex Triggers
Basic Structure:
trigger AccountTrigger on Account (before insert, after insert, before update, after update, before delete, after delete) { if (Trigger.isBefore) { if (Trigger.isInsert) { // code } } }
Context Variables:
Trigger.new
: New records in insert/updateTrigger.old
: Old records in update/deleteTrigger.newMap
,Trigger.oldMap
: Maps of IDs to records
Batch Apex
Batch Class:
global class BatchExample implements Database.Batchable<sObject> { global Database.QueryLocator start(Database.BatchableContext bc) { return Database.getQueryLocator([SELECT Id FROM Account]); } global void execute(Database.BatchableContext bc, List<Account> scope) { // code } global void finish(Database.BatchableContext bc) { // code } }
Executing Batch:
BatchExample batch = new BatchExample(); Database.executeBatch(batch);
Apex Scheduler
Scheduler Class:
global class ScheduledClass implements Schedulable { global void execute(SchedulableContext sc) { // code } }
Scheduling:
String cronExp = '0 0 12 * * ?'; // Every day at noon System.schedule('Daily Job', cronExp, new ScheduledClass());
Asynchronous Apex
Future Method:
@future public static void doFutureWork() { // code }
Queueable Apex:
public class QueueableExample implements Queueable { public void execute(QueueableContext context) { // code } } System.enqueueJob(new QueueableExample());
Custom Metadata Types
Define Metadata:
CustomMetadataType__mdt metadata = new CustomMetadataType__mdt(); metadata.DeveloperName = 'CustomSetting'; metadata.Label = 'Custom Setting';
Query Metadata:
List<CustomMetadataType__mdt> mdList = [SELECT DeveloperName, Label FROM CustomMetadataType__mdt];
Best Practices
- Bulkify Your Code: Always write code to handle multiple records.
- Avoid SOQL/DML in Loops: Move queries and DML operations outside loops.
- Use Collections: Use lists, sets, and maps to efficiently process records.
- Handle Exceptions: Always use try-catch blocks to manage exceptions.
- Use Custom Settings: Store and manage configuration data outside of code.
- Test Coverage: Write thorough unit tests to ensure at least 75% code coverage.
This cheat sheet covers essential aspects of Apex development, offering a solid foundation for anyone looking to master Salesforce Apex coding.
0 Comments