Sub topic 1
What Apex Is and Where It Runs
Prerequisites
This chapter assumes you know the basic Salesforce data model (objects, fields, and records) and can find your way around the Setup menu. You should also know basic programming ideas such as variables, loops, and collections. You don't need to have written Apex before.
What Apex is
Apex is Salesforce's programming language for custom business logic. It is strongly typed, so every variable has a declared type that the compiler checks. It is object-oriented, so you organize code into classes with methods and fields. Its syntax looks a lot like Java.
Apex is also tied closely to the Salesforce data model. Objects such as Account and Contact are types you use directly in code, and SOQL (Salesforce Object Query Language) queries are part of the language itself.
Where Apex runs
Apex does not run on your computer or on a server you manage. You write it, and Salesforce stores it as metadata in your org. The platform compiles it and runs it on Salesforce servers. This is why Apex is called multitenant code: many customers share the same infrastructure. To keep one customer's code from using too many shared resources, Salesforce enforces governor limits. A later chapter covers them in detail.
Apex runs in response to events. Common entry points are:
- Triggers, which run before or after records are inserted, updated, deleted, or undeleted.
- Invocable methods, which a flow can call as an action.
- Asynchronous jobs, such as Queueable and Batch Apex, which run later in the background.
- Web service endpoints and Lightning components, which let outside systems and user interfaces call your code.
A first example: a trigger
A trigger is Apex code attached to an object. This one runs after contacts are inserted and keeps a count of contacts on each account. It assumes a custom number field Contact_Count__c exists on Account.
trigger ContactTrigger on Contact (after insert) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
List<Account> toUpdate = new List<Account>();
for (AggregateResult ar : [
SELECT AccountId acctId, COUNT(Id) total
FROM Contact
WHERE AccountId IN :accountIds
GROUP BY AccountId
]) {
toUpdate.add(new Account(
Id = (Id) ar.get('acctId'),
Contact_Count__c = (Integer) ar.get('total')
));
}
update toUpdate;
}Notice four things:
Trigger.newis a list. A trigger receives all records in the operation, up to 200 at a time, not one record.- The code collects account IDs into a
Set, then runs one query for all of them. - The query uses
IN :accountIds. The colon passes an Apex variable into SOQL. - The code updates all accounts with one
updatestatement after the loop.
Keeping the query and the update outside the loop is called bulk-safe design. A later chapter explains why it matters.
Testing is part of the language
Apex has built-in testing. A class marked @IsTest holds test methods, and these run in the org. Salesforce requires at least 75% overall code coverage before Apex can be deployed to production. This test inserts 200 contacts in one operation to check that the trigger works in bulk.
@IsTest
private class ContactTriggerTest {
@IsTest
static void countsContactsInBulk() {
Account a = new Account(Name = 'Acme');
insert a;
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < 200; i++) {
contacts.add(new Contact(LastName = 'Contact ' + i, AccountId = a.Id));
}
insert contacts;
a = [SELECT Contact_Count__c FROM Account WHERE Id = :a.Id];
Assert.areEqual(200, a.Contact_Count__c);
}
}Common errors for newcomers
- Treating a trigger as single-record code. Code that works when you save one record can fail when a data load sends 200.
- Putting SOQL or DML inside a loop. Each call counts against governor limits, so a large batch can fail with a limit error.
- Assuming a field exists. The example fails to compile if
Contact_Count__cis missing fromAccount.
Exercise
In the trigger above, why does the code collect account IDs in a Set and run one query, instead of querying inside the for loop over Trigger.new?
Show answer
A trigger can receive up to 200 records at once. A query inside the loop would run once per record and count against the governor limit on SOQL queries. Collecting IDs first lets one aggregate query handle all records, so the trigger stays bulk-safe.