What we do
Tools
Industries
Department
How we workLet's talk →
Home/Salesforce/Apex Class
Salesforce Apex

What an Apex Class Is, and How to Write and Test One

An Apex class is a named block of code, written in Salesforce's own Java-like language, that holds methods and variables and runs on Salesforce's servers. Triggers, batch jobs, Flow actions and REST endpoints all call into classes. Below: a minimal class, where to create it, the test class Salesforce demands before production, and the cases where Apex has nothing to connect to.

The short version

A class declaration looks like public with sharing class InvoiceTotals { }. Methods go inside the braces, for example public static Decimal openBalance(Id accountId) { ... }.

with sharing makes the class respect the running user's record access. Leave it off and the class runs in system context, which sees everything.

In VS Code with the Salesforce Extension Pack, open the Command Palette and run:

SFDX: Create Apex Class

In the browser, open the Developer Console from the gear menu, then:

File New Apex Class

Before it can reach production, your org's Apex needs at least 75% test coverage overall, and every trigger needs some.

The parts of a class you will actually touch

Access modifiers. private is visible only inside the class, public inside your org's code, and global to anything outside it, including managed packages and some web service calls. Start with public and widen only when something genuinely needs it.

Static or instance. A static method is called on the class itself (InvoiceTotals.openBalance(acctId)). An instance method needs new InvoiceTotals() first and is the better choice when the object carries state between calls.

Sharing keywords. with sharing, without sharing and inherited sharing decide whose record access the code runs under. inherited sharing takes on the caller's setting, which suits utility classes called from many places.

Classes vs. triggers. A trigger fires before or after a record is inserted, updated, deleted or undeleted. Keep the trigger thin and have it hand Trigger.new to a class that does the work. The class can be tested and reused. Logic written inside the trigger body can't be reused anywhere else.

Writing your first class against real records

The example totals unpaid invoice amounts for an account. Swap in your own object and field names.

  1. 1

    Create the class

    SFDX: Create Apex Class

    Name it InvoiceTotals. VS Code writes the .cls file and a matching .cls-meta.xml file that holds the API version. Keep both in source control.

  2. 2

    Query in bulk, not one record at a time

    Give the method a set of account IDs, run one SOQL query such as [SELECT Account__c, Amount__c FROM Invoice__c WHERE Account__c IN :accountIds AND Paid__c = false], then add up the amounts in a map keyed by account ID.

    Watch for: a query inside a for loop. It passes with one test record and fails the day someone imports two hundred.

  3. 3

    Loop with the types Apex gives you

    The usual form is for (Invoice__c inv : invoices) { ... }. A SOQL for loop, for (Invoice__c inv : [SELECT ...]), fetches records in chunks, which helps when the result set is large.

  4. 4

    Branch with switch instead of long if/else chains

    Apex's case statement is switch on, for example switch on inv.Status__c { when 'Overdue' { ... } when 'Disputed', 'On hold' { ... } when else { ... } }. It works on strings, integers, enums and sObject types.

  5. 5

    Call it from where the work starts

    A trigger on Invoice__c, a Flow (add @InvocableMethod to a static method so Flow Builder lists it as an action), a scheduled job, or a Lightning component via @AuraEnabled. The class stays the same. Only the entry point changes.

The test class that gets it to production

Coverage is the gate, but the asserts are what catch a broken change next quarter.

  1. 1

    Mark it as a test

    Create a second class, InvoiceTotalsTest, annotated @isTest. Test classes don't count against your org's code size limit and by default they can't see your org's records, so each test starts with only the data it creates.

  2. 2

    Build the data the test needs

    Insert an account and a few invoices inside the test, or put shared records in a method annotated @testSetup so every test method in the class gets them.

  3. 3

    Run the code between startTest and stopTest

    Wrap the call in Test.startTest(); and Test.stopTest();. The code inside gets a fresh set of governor limits, and any asynchronous work it queues, such as a batch job, runs when stopTest() is reached.

  4. 4

    Assert the outcome

    Check the actual numbers with Assert.areEqual(450, result.get(acct.Id));. Older code uses System.assertEquals, which still works. Add a test for the empty case and the many-records case, not just the happy path.

    Watch for: test methods with no asserts. They raise coverage and prove nothing.

  5. 5

    Run it and read the coverage

    SFDX: Run Apex Tests

    From the terminal, sf apex run test --class-names InvoiceTotalsTest --code-coverage --result-format human prints pass or fail and the coverage for each class.

Which kind of Apex suits the job

The job Write it as Watch for
Logic that runs on every save of a record A trigger that calls a handler class Flows and triggers on the same object both firing. Decide which one owns each field.
A nightly cleanup or recalculation across thousands of records Batch Apex: a class implementing Database.Batchable<sObject> with start, execute and finish Each chunk is its own transaction. One failed chunk doesn't roll back the others.
Work that should happen after the save, like calling another system A Queueable class, started with System.enqueueJob Callouts from a trigger must be asynchronous. Salesforce blocks them in the save itself.
A step an admin wants inside a Flow A static method marked @InvocableMethod It receives a list, because Flow sends records in bulk.
Another system needs to push data into Salesforce A class annotated @RestResource with @HttpPost methods Check whether the standard REST API already does it before writing your own endpoint.

Batch Apex in brief

start returns a query locator for the records to process. execute receives one chunk at a time, 200 records by default. finish runs once at the end, a good place to send a summary email or chain the next job. You start it with Database.executeBatch(new RecalcInvoices(), 200); and can watch progress under Apex Jobs in Setup.

A batch class needs its own test like any other. Insert fewer than 200 records so the test runs a single chunk, call Database.executeBatch between Test.startTest() and Test.stopTest(), then assert on the records afterwards.

Apex callouts: what trips people up

Calling a REST or SOAP API from Apex is normal, well-supported work. These are the parts tutorials skip.

The callout is blocked before it leaves

How you'll know: An "Unauthorized endpoint" error on the first real run.

Fix: Register the host as a Named Credential, which also keeps the login details out of your code, or as a Remote Site Setting for simple cases.

The test fails because it tried to call out

How you'll know: "Methods defined as TestMethod do not support Web service callouts."

Fix: Write a class that implements HttpCalloutMock, return a fake response from it, and register it with Test.setMock before the call.

The other system has nothing to call

How you'll know: The vendor portal or older internal tool has a login screen and no API documentation at all.

Fix: No amount of Apex fixes this. The work moves to the other side: automate the portal the way a person uses it, then post the result into Salesforce through the Salesforce API or your own @RestResource class.

Questions people ask

What is an Apex class used for in Salesforce?

Holding logic that's too complex or too heavy for Flow: bulk processing, validation that spans several objects, calls to outside APIs, custom REST endpoints and the code behind Lightning components. Triggers and Flows call into classes to get that work done.

Do I need Apex, or is Flow enough?

If the job is a few conditions and some field updates, Flow is enough, and an admin can maintain it later. Apex earns its place for loops over large record sets, integrations that need real error handling, and logic a point-and-click builder can't express. Our Salesforce developer page covers that call in more depth.

What is a batch Apex class?

A class that implements Database.Batchable so Salesforce processes a large set of records in chunks, each in its own transaction, which keeps the job inside governor limits. Nightly recalculations and data cleanups are the usual uses.

Why does Apex need a test class to deploy?

Salesforce won't deploy Apex to production unless tests cover at least 75% of your org's Apex code and every test passes. The rule exists to catch breaking changes before they reach live data, so a test that asserts real results is worth far more than one written only to raise the percentage.

Can Apex connect Salesforce to a system that has no public API?

No. A callout needs an endpoint, REST or SOAP. If the other system never exposed one, the practical route is automating its own screens and feeding the result into Salesforce. That's work n-frames does regularly.

Is Apex hard to learn if I know Java or C#?

The syntax will feel familiar: classes, interfaces, strong typing, try/catch. The new parts are SOQL queries written inline, governor limits on every transaction, and the test coverage rule. Trailhead's Apex modules and a free Developer Edition org are the usual places to practice.

Let's talk

Tell us the one thing your team does manually that eats up time. We read every message and reply within a day.