Salesforce Apex practice exercises with solutions
Practise Apex on a realistic data model: queries, bulk-safe triggers, handler classes, async processing, actions for Flow and Agentforce, and tests. Write the code yourself in VS Code or the Developer Console before opening the model answers.
All exercises use the data model from our real estate practice project: Property__c, Buyer__c, Agent__c, Property_Agent__c and Property_Offer__c. Build Task 1 of that project first (about an hour), in a free Developer Edition org. Each exercise has a level, a check so you know it works, and a model answer to open after you have tried.
Exercises
1. A query method
BeginnerWrite a class PropertyService with a method that returns properties in a given city priced below a maximum, cheapest first.
- Run it in Anonymous Apex with a city and price and print the results.
Show a model answer
public with sharing class PropertyService {
public static List<Property__c> findInCity(String city, Decimal maxPrice) {
return [
SELECT Id, Name, City__c, Asking_Price__c
FROM Property__c
WHERE City__c = :city AND Asking_Price__c <= :maxPrice
WITH USER_MODE
ORDER BY Asking_Price__c ASC
LIMIT 200
];
}
}Bind variables (:city) prevent SOQL injection. WITH USER_MODE applies the user's object and field permissions.
2. Before trigger: block offers on sold properties
BeginnerWrite a before insert trigger on Property_Offer__c that adds an error to any offer whose property is Sold. It must work for 200 offers at once.
- Inserting a list of offers with some on sold properties fails only those records (use
Database.insert(list, false)to see this).
Show a model answer
trigger PropertyOfferTrigger on Property_Offer__c (before insert) {
Set<Id> propIds = new Set<Id>();
for (Property_Offer__c o : Trigger.new) propIds.add(o.Property__c);
Map<Id, Property__c> props = new Map<Id, Property__c>(
[SELECT Id, Status__c FROM Property__c WHERE Id IN :propIds]);
for (Property_Offer__c o : Trigger.new) {
Property__c p = props.get(o.Property__c);
if (p != null && p.Status__c == 'Sold') {
o.addError('This property is already sold.');
}
}
}One query for all records, using a set and a map, is the bulkification pattern interviewers expect.
3. After update: reject other offers
IntermediateWhen an offer changes to Accepted, set all other open offers on that property to Rejected. Move the logic into a handler class.
- Accept one of three offers: the other two are Rejected.
- Updating 200 offers in one transaction stays within limits.
Show a model answer
public with sharing class PropertyOfferHandler {
public static void afterUpdate(List<Property_Offer__c> news, Map<Id, Property_Offer__c> olds) {
Set<Id> propIds = new Set<Id>();
Set<Id> acceptedIds = new Set<Id>();
for (Property_Offer__c o : news) {
if (o.Status__c == 'Accepted' && olds.get(o.Id).Status__c != 'Accepted') {
propIds.add(o.Property__c);
acceptedIds.add(o.Id);
}
}
if (propIds.isEmpty()) return;
List<Property_Offer__c> others = [
SELECT Id FROM Property_Offer__c
WHERE Property__c IN :propIds AND Id NOT IN :acceptedIds
AND Status__c NOT IN ('Rejected', 'Accepted')];
for (Property_Offer__c o : others) o.Status__c = 'Rejected';
update others;
}
}Call it from the trigger with PropertyOfferHandler.afterUpdate(Trigger.new, Trigger.oldMap);. Checking the old value means the logic runs only on the change, which also prevents recursion when the handler updates other offers.
4. An invocable action for Flow and Agentforce
IntermediateWrite an invocable method that takes an offer amount and an agent ID and returns the estimated commission.
- Call it from a flow with an Action element.
- The same action can be added to an Agentforce topic.
Show a model answer
public with sharing class CommissionAction {
public class Request {
@InvocableVariable(required=true description='Offer amount')
public Decimal amount;
@InvocableVariable(required=true description='Agent record ID')
public Id agentId;
}
public class Result {
@InvocableVariable(description='Estimated commission')
public Decimal commission;
}
@InvocableMethod(label='Estimate Commission' description='Estimates agent commission for an offer amount')
public static List<Result> run(List<Request> reqs) {
Set<Id> ids = new Set<Id>();
for (Request r : reqs) ids.add(r.agentId);
Map<Id, Agent__c> agents = new Map<Id, Agent__c>(
[SELECT Id, Commission_Rate__c FROM Agent__c WHERE Id IN :ids]);
List<Result> out = new List<Result>();
for (Request r : reqs) {
Result res = new Result();
Agent__c a = agents.get(r.agentId);
res.commission = (a == null || a.Commission_Rate__c == null) ? 0
: r.amount * a.Commission_Rate__c / 100;
out.add(res);
}
return out;
}
}Invocable methods receive a list, because Flow bulkifies calls. In Apex, a percent field holds the number shown (2.5 for 2.5%), so divide by 100 here, unlike in formulas. Agentforce reads the labels and descriptions to decide when to call the action.
5. Batch Apex: archive stale listings
AdvancedWrite a batch class that sets Status to Withdrawn on properties listed more than 180 days ago with no offers, and a schedulable class that runs it every Sunday night.
- Run the batch from Anonymous Apex and check Apex Jobs.
- Schedule it and see it in Scheduled Jobs.
Show a model answer
public class StaleListingBatch implements Database.Batchable<SObject>, Schedulable {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
SELECT Id FROM Property__c
WHERE Listing_Date__c < LAST_N_DAYS:180
AND Offers_Received__c = 0 AND Status__c = 'Available']);
}
public void execute(Database.BatchableContext bc, List<Property__c> scope) {
for (Property__c p : scope) p.Status__c = 'Withdrawn';
update scope;
}
public void finish(Database.BatchableContext bc) {}
public void execute(SchedulableContext sc) {
Database.executeBatch(new StaleListingBatch(), 200);
}
}
// Schedule: System.schedule('Stale listings', '0 0 23 ? * SUN', new StaleListingBatch());6. Test class
IntermediateWrite tests for exercise 3: one test with a single accepted offer, and a bulk test with 200 offers.
- Tests pass and assert the results, not just the coverage.
Show a model answer
@IsTest
private class PropertyOfferHandlerTest {
@TestSetup
static void setup() {
Property__c p = new Property__c(Name = 'Test', Asking_Price__c = 100000, Status__c = 'Available');
insert p;
Buyer__c b = new Buyer__c(Name = 'Buyer');
insert b;
List<Property_Offer__c> offers = new List<Property_Offer__c>();
for (Integer i = 0; i < 200; i++) {
offers.add(new Property_Offer__c(Property__c = p.Id, Buyer__c = b.Id,
Offer_Amount__c = 90000 + i, Status__c = 'Submitted'));
}
insert offers;
}
@IsTest
static void acceptingOneRejectsTheRest() {
Property_Offer__c first = [SELECT Id FROM Property_Offer__c LIMIT 1];
first.Status__c = 'Accepted';
Test.startTest();
update first;
Test.stopTest();
Assert.areEqual(199, [SELECT COUNT() FROM Property_Offer__c WHERE Status__c = 'Rejected']);
}
}Set the required fields of your own objects in the test data. Test.startTest and stopTest give the code under test a fresh set of governor limits.
Keep going
Common questions
01Do I need VS Code for these exercises?
Do I need VS Code for these exercises?
No. The Developer Console in your org works for all of them. VS Code with the Salesforce Extensions and the Salesforce CLI is what you will use on real projects, so it is worth setting up.
02Why are all the examples bulkified?
Why are all the examples bulkified?
Triggers and invocable methods can receive up to 200 records at a time, from imports, integrations or Flow. Code that queries or updates inside a loop hits governor limits, and interviewers check for this first.