Sub topic 16
Choosing the right construct
This chapter assumes you can write Apex classes with fields, methods, and constructors. It also assumes you know how static, interfaces, virtual, abstract, and override work, and that you know Apex code runs inside transactions. Here you decide which of those tools fits a given problem.
Four questions that narrow the choice
Most design choices in Apex come down to four questions, asked in order.
- Does the code need data that belongs to one object? If yes, use an instance method.
- Does the code need to be swapped for another implementation, such as a test double or a different rule? If yes, use an interface.
- Do several classes share real code, not only a method signature? If yes, consider a
virtualorabstractbase class. - If none of those apply, is it a stateless helper? Then a
staticmethod is fine.
When static is the right choice
A static method suits pure functions: the output depends only on the arguments, and nothing is remembered between calls. String formatting, null-safe parsing, and simple math fit this shape.
public class StringUtil {
public static String initials(String fullName) {
if (String.isBlank(fullName)) {
return '';
}
String result = '';
for (String part : fullName.trim().split('\\s+')) {
result += part.substring(0, 1).toUpperCase();
}
return result;
}
}
// Usage
System.debug(StringUtil.initials('ada lovelace')); // ALA static method has costs you should accept knowingly:
- A caller cannot substitute it. Code that calls
StringUtil.initials(...)is welded to that class. - Static methods are not polymorphic. A subclass cannot override one.
- Static variables hold state for the whole transaction. Hidden shared state makes methods depend on call order.
Use static for stateless helpers, factory methods such as createStartingAt, constants, and a small number of transaction-wide flags. Avoid it for business rules that might change or need to be faked in tests.
When an instance is the right choice
Use an instance when the behavior depends on values that differ per object, or when you want to inject those values through a constructor. An instance also gives you a clean place to hold configuration without using global variables.
Instance state has a lifetime to watch in Batch Apex. Each execute call runs as its own transaction, so static variables reset between batches. An instance variable on the batch class survives only if the class implements Database.Stateful. Static fields are never a substitute for it.
public class TotalsBatch implements Database.Batchable<SObject>, Database.Stateful {
private Decimal runningTotal = 0; // kept across execute() calls
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Amount FROM Opportunity WHERE Amount != null');
}
public void execute(Database.BatchableContext bc, List<Opportunity> scope) {
for (Opportunity o : scope) {
runningTotal += o.Amount;
}
}
public void finish(Database.BatchableContext bc) {
System.debug('Total: ' + runningTotal);
}
}When an interface is the right choice
Choose an interface when callers should depend on a contract, not a class. The strongest practical reason in Apex is testing. Static calls cannot be faked without the Stub API, but an object passed through a constructor can be replaced with a small test class.
public interface TaxCalculator {
Decimal tax(Decimal amount);
}
public class FlatTax implements TaxCalculator {
public Decimal tax(Decimal amount) {
return amount * 0.2;
}
}
public class InvoiceService {
private final TaxCalculator calculator;
public InvoiceService(TaxCalculator calculator) {
this.calculator = calculator;
}
public Decimal total(Decimal net) {
return net + calculator.tax(net);
}
}
@IsTest
private class InvoiceServiceTest {
private class ZeroTax implements TaxCalculator {
public Decimal tax(Decimal amount) {
return 0;
}
}
@IsTest
static void totalAddsTax() {
InvoiceService svc = new InvoiceService(new ZeroTax());
Assert.areEqual(100, svc.total(100));
}
}InvoiceService never mentions FlatTax. Production code passes new FlatTax(), and the test passes a stub. The test needs no data setup and no callouts.
Interfaces also fit these cases:
- A class must play several roles. A class can implement many interfaces but extend only one class.
- A framework expects a contract, as with
Comparable,Database.Batchable,Queueable, andSchedulable. - Different teams or packages implement the same contract independently.
When a base class is the right choice
Inheritance is for sharing implementation among classes that really are variants of one concept. Use abstract when the parent cannot function alone and forces subclasses to fill in a method. Use virtual when the parent has a sensible default that subclasses may replace.
The risks are tight coupling and a single inheritance slot. A subclass depends on the parent's internals, and a parent change can break every child. Because Apex allows one parent, spending it on a base class rules out any other parent.
A common compromise is to publish an interface for callers and use an abstract class internally to avoid duplicating code:
public interface Notifier {
void send(String message);
}
public abstract class BaseNotifier implements Notifier {
public void send(String message) {
if (String.isBlank(message)) {
return;
}
deliver(format(message));
}
protected virtual String format(String message) {
return message.trim();
}
protected abstract void deliver(String text);
}
public class DebugNotifier extends BaseNotifier {
protected override void deliver(String text) {
System.debug(text);
}
}
// Usage
Notifier n = new DebugNotifier();
n.send(' hello '); // helloCallers see only Notifier. The blank check lives in one place. A new channel needs only one deliver method.
Comparison at a glance
| Need | Static method | Instance method | Interface | Base class |
|---|---|---|---|---|
| Per-object state | No | Yes | Via implementers | Yes |
| Swappable in tests | Hard | Yes, if injected | Yes | Partly |
| Polymorphic dispatch | No | Only via inheritance | Yes | Yes |
| Shares code | Via calls | Via composition | No | Yes |
| Coupling for callers | High | Medium | Low | Medium to high |
Common mistakes
Using a static Boolean as a recursion guard. A single flag such as hasRun blocks every later call in the transaction. A bulk DML of more than 200 records fires the trigger once per chunk of 200, so the second chunk would be skipped. Track record Ids instead:
public class RecordGuard {
private static Set<Id> processed = new Set<Id>();
// Returns true the first time an Id is seen in this transaction.
public static Boolean markIfNew(Id recordId) {
return processed.add(recordId);
}
}Treating static state as a cache across users or requests. Static values disappear when the transaction ends. For longer-lived data, use Platform Cache or a custom setting.
Making everything static for convenience. The code compiles and runs, but every caller is now locked to one implementation.
Inheriting for reuse alone. If the subclass is not truly a kind of the parent, pass the helper in as a field (composition) instead of extending.
Over-building interfaces. An interface with one implementation and no test need adds files and no flexibility. Add it when a second implementation or a test double actually appears.
Summary rules of thumb
- Static for stateless helpers, factories, and constants.
- Instance when behavior depends on per-object data.
- Interface for contracts, framework hooks, and test seams.
- Abstract or virtual base class for shared implementation inside one family.
- Combine an interface for callers with an abstract class for implementers when both needs exist.
Exercise
A trigger handler uses private static Boolean hasRun = false; to avoid running twice. A data load of 500 Accounts updates only the first 200. Explain why, and give a safer design.
Show answer
Trigger code runs once per chunk of 200 records within the same transaction. The first chunk sets hasRun to true, so the handler skips chunks two and three. A safer design keeps a static Set<Id> of processed record Ids and processes only Ids for which add returns true. That way each record runs once and every chunk is still handled.
Exercise
You have OrderService.calculateShipping(Order o) as a static method called from many classes. Product asks for a different shipping rule per region, and you need unit tests that do not depend on the real rules. What would you change?
Show answer
Define a ShippingCalculator interface with a calculate(Order o) method. Write one implementing class per rule. Make OrderService an instance class that receives a ShippingCalculator through its constructor, and have callers pass the right implementation for the region. Tests then pass a small stub class. A static method cannot be swapped this way, and it is not polymorphic.