Sub topic 1
What Apex Is and Where It Runs
Apex is the programming language Salesforce built for writing custom business logic on its own platform. This chapter covers what kind of language it is, where your code executes, and how code gets started. The later chapters build on this when they compare Apex with Flow.
Prerequisites
This chapter assumes you have:
- A working knowledge of the Salesforce data model: objects, fields, records, and relationships.
- Familiarity with the Setup menu, including how to find Object Manager and Apex Classes.
- Some exposure to building a simple Flow or workflow-style automation.
- Basic programming concepts: variables, loops, and collections such as lists and maps.
You do not need to know Java. Apex looks like Java, and this chapter points out where the two differ.
What Apex is
Apex is a strongly typed, object-oriented language. Each term has a practical consequence:
- Strongly typed: every variable has a declared type, such as
Integer,String,Account, orList<Contact>. The compiler rejects mismatches before the code ever runs. - Object-oriented: you organize code into classes and interfaces, with methods, properties, inheritance, and access modifiers like
public,private, andglobal. - Compiled: Salesforce compiles your source into an internal form when you save it. A compile error stops the save.
- Case-insensitive:
account,Account, andACCOUNTrefer to the same thing. This surprises developers coming from Java.
Apex differs from a general-purpose language because the database is part of the language. Salesforce objects are built-in types, so you can use Account or Opportunity as you would use String. You can query and change data without a driver or an ORM (object-relational mapping library):
- SOQL (Salesforce Object Query Language) is written inline in square brackets.
- DML (Data Manipulation Language) statements such as
insert,update,upsert,delete, andundeletechange records.
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Name LIKE 'Acme%' LIMIT 10];
for (Account a : accounts) {
a.Description = 'Reviewed';
}
update accounts;The compiler checks the query. If you misspell a field name inside the brackets, the save fails. A runtime failure becomes a compile-time failure, which is a real advantage over building SQL strings by hand.
Where Apex runs
Apex does not run on your laptop, in a browser, or in a container you manage. It runs on Salesforce servers, inside the same multitenant platform that stores your data. Many customer organizations (orgs) share the same infrastructure, and the platform keeps one customer from consuming resources that others need.
That has three consequences.
- You cannot run Apex locally. You write it locally if you like, but you save it to an org, and the org compiles and runs it. Tests also run in the org.
- Resources are limited per transaction. Salesforce enforces governor limits on queries, DML statements, CPU time, and heap memory. The next chapters cover them in depth. For now, accept that Apex is metered.
- Code is metadata. Classes and triggers are stored in the org as metadata, like custom fields and flows. You move them between orgs by deploying, not by copying a file onto a server.
Changing code in production
You normally cannot edit Apex directly in a production org. Salesforce expects you to develop in a sandbox or scratch org, test there, and deploy to production. (Sandboxes are copies of an org, and scratch orgs are short-lived orgs you create from configuration.) Production deployments also require passing tests, which the testing chapter covers.
How Apex code is organized
Apex has two main kinds of source file. A third kind, anonymous Apex, is for one-off scripts.
| Kind | Purpose | Notes |
|---|---|---|
| Class | Reusable logic: methods, properties, inner classes | Holds most of your code. Can be `public`, `global`, or `private` (inner classes and tests). |
| Trigger | Runs when records change | Attached to one object. Declares events such as `before insert` or `after update`. |
| Anonymous Apex | A script you run once | Used for exploration and data fixes. Not saved as a class. |
A class
public with sharing class AccountService {
public static List<Account> findByNamePart(String namePart) {
String pattern = '%' + namePart + '%';
return [
SELECT Id, Name
FROM Account
WHERE Name LIKE :pattern
ORDER BY Name
LIMIT 50
];
}
}The colon in :pattern is a bind variable. Apex passes the value to the query safely, so this form does not allow SOQL injection the way string concatenation into a dynamic query could.
A trigger
A trigger is a block of code attached to an object that Salesforce runs when a record event occurs. This one fills in a default description before the record is saved.
trigger AccountDefaults on Account (before insert) {
for (Account a : Trigger.new) {
if (String.isBlank(a.Description)) {
a.Description = 'New account';
}
}
}Two details matter here. Trigger.new is a list, because a trigger receives a batch of records, not one. In a before trigger you change the records directly and need no update statement, because the platform saves them afterward. Chapter 6 covers why the batch shape matters.
Anonymous Apex
You can run a script in the Developer Console (Debug, then Open Execute Anonymous Window) or from VS Code. It is the fastest way to try a query or call a method:
List<Account> found = AccountService.findByNamePart('Acme');
System.debug('Found ' + found.size() + ' accounts');Check the output in the debug log. Anonymous Apex runs in the same environment as saved code, with the same limits.
What starts Apex running
Apex never runs on its own. Something must call it, and that something is an entry point. The entry point also determines which limits apply and what context variables exist.
| Entry point | How it starts | Typical use |
|---|---|---|
| Trigger | A record is inserted, updated, deleted, or undeleted | Validation, defaulting, maintaining related records |
| `@InvocableMethod` | A flow, Process Builder process, or REST call invokes it | Giving Flow access to custom logic |
| `@AuraEnabled` method | A Lightning web component or Aura component calls it | Server logic for custom UI |
| REST or SOAP service | An external system sends an HTTP request | Custom APIs for integrations |
| Batch Apex | A job processes records in chunks | Large data volumes |
| Queueable Apex | Code enqueues a job | Asynchronous work, chained jobs |
| Scheduled Apex | A schedule or cron expression fires | Nightly maintenance |
| `@future` method | Code calls it and it runs later | Simple asynchronous callouts |
| Email service | An inbound email arrives | Processing incoming messages |
| Test method | A test run starts it | Verification and deployment coverage |
The @InvocableMethod row is the link to Flow. A flow can call Apex as an action. Chapter 11 covers that in detail.
The transaction model
Apex executes inside a transaction: a unit of work that either commits in full or rolls back in full. When a user saves an Account, Salesforce starts a transaction. It runs validation, triggers, flows, and other automation, and then commits. If any step throws an unhandled exception, the platform rolls back every database change made in that transaction, including changes made by other automation on the same record.
Two points follow:
- Apex that you call from a trigger shares the transaction and the limits with everything else in it. Chapter 5 covers this.
- Asynchronous Apex (batch, queueable, scheduled, future) starts a new transaction with its own limits.
The order in which a save runs these steps is the order of execution. Chapter 7 covers it.
Sharing and security context
By default, Apex runs in system mode. It can read and write data without checking the running user's object permissions or field-level security. Record sharing is controlled by the class declaration:
with sharingenforces the running user's record-level access (sharing rules, role hierarchy, and so on).without sharingignores record sharing.inherited sharinguses the sharing setting of the class that called it.
If you omit the keyword, the class behaves like without sharing when it is the entry point, which is rarely what you want. Declare the sharing mode explicitly on every class.
Sharing keywords do not enforce field-level security or object permissions. To enforce those in a query, add WITH USER_MODE:
List<Contact> contacts = [
SELECT Id, LastName, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
];A user without read access to Email gets an error instead of the data. Flow has its own context rules. Record-triggered flows can run in system context or user context depending on how they are configured, so you decide this for each tool.
Development tools and workflow
You can write Apex in several places:
- VS Code with the Salesforce Extensions Pack: the standard choice for real projects. It gives you source control, code completion, and deployment through the Salesforce CLI.
- Developer Console: a browser tool that is good for quick tests, anonymous Apex, and reading debug logs.
- Setup: you can create a class or trigger from the Apex Classes page in a sandbox or developer org.
A common workflow looks like this:
- Create a scratch org or use a sandbox.
- Write the class or trigger and its test class.
- Run tests and read the debug logs.
- Commit the source to version control.
- Deploy to a higher environment, then to production.
Because Apex lives in source files, you get version history, code review, and automated deployment. This is a main reason teams choose Apex for complex logic, and a later chapter weighs it against the maintenance cost.
Common errors for newcomers
- Forgetting that triggers receive lists. Code that reads
Trigger.new[0]and ignores the rest works for one record and fails during data loads. - Using
without sharingby accident. An undeclared sharing mode can expose records a user should not see. - Putting SOQL or DML inside a loop. It works for one record and breaks when a trigger receives 200. The bulkification chapter explains this.
- Expecting a local runtime. Code only runs after you save it to an org.
- Treating Apex as exempt from automation conflicts. A trigger and a flow on the same object and event both run in the same transaction.
Summary
Apex is a compiled, strongly typed, object-oriented language that runs on Salesforce servers. Its main traits are:
- It has built-in SOQL and DML.
- It lives in the org as metadata.
- It runs only when an entry point such as a trigger, flow action, or API call starts it.
- It executes inside a transaction with enforced limits.
- It runs in system mode unless you restrict it.
With that model in place, the next chapter looks at Flow.
Exercise
A teammate says, "I'll write a trigger on Contact that reads Trigger.new[0].AccountId and updates that account." Name two problems with this approach and say what you would change.
Show answer
First, a trigger receives a list of records, not a single record. Reading only index 0 ignores the other records when a data load inserts up to 200 contacts in one batch. Second, the code reads a single record's data and implies one query or update per record, which does not scale within governor limits. Change it to loop over Trigger.new, collect the AccountId values into a Set, and then run one query and one update for the whole set. A declared sharing mode on any helper class is also advisable.
Exercise
You save an Apex class in a production org by editing it directly in Setup, and the save is rejected. Why does this happen, and what is the normal workflow?
Show answer
Salesforce does not allow direct edits to Apex in production. Code must be developed in a sandbox, scratch org, or developer org, tested, and then deployed to production. Deployment to production requires passing tests. The usual workflow is to write the class and its test, run the tests, commit to version control, and deploy through the CLI or a change set.
Exercise
A class is declared as public class ReportHelper with no sharing keyword and is called from a Lightning web component. What risk does this create, and how do you fix it?
Show answer
Without a keyword, sharing behavior is not stated in the code, and a class that is the entry point may not enforce the user's record access. This can expose records the user should not see. Fix it by declaring with sharing (or inherited sharing where it is a helper). Add WITH USER_MODE to queries if object and field permissions must also be enforced.