Sub topic 16
Choosing the right construct
This chapter assumes you can declare Apex classes and know the difference between static and instance members. It also assumes you have seen interfaces, virtual and abstract classes, and override. Here you learn how to pick among them.
Start with the question you are answering
Four constructs cover most design decisions in Apex. Each answers a different question.
| Construct | Ask yourself | Typical example |
|---|---|---|
| Static method | Does this need no per-object data? | A `StringUtil.clean(String)` helper |
| Instance method | Does the behavior depend on an object's own fields? | `Counter.increment()` |
| Interface | Do several classes need to be used interchangeably, with no shared code? | `Discount` |
| Base class (`virtual` or `abstract`) | Do related classes share fields or code, and also differ in a few steps? | `Shape` |
Static or instance
Use a static method when the result depends only on its parameters. It needs no object and is easy to call. Use an instance method when the behavior reads or changes the object's fields.
Static state is shared by everything in the current transaction. That makes it useful for a recursion guard such as TriggerGuard.shouldRun(), and risky for anything else. A static variable that holds business data can be changed from any code running in the transaction, which makes bugs hard to trace. It also resets on every new transaction, so it cannot carry data between transactions.
Static methods have a testing cost. Calling code is tied to the exact class name, so a test cannot substitute a different implementation. If you expect to replace the logic in tests, put it behind an interface instead.
Interface or inheritance
Choose an interface when you only need a contract. In the Discount example, PercentDiscount and FlatDiscount share no code. The caller only needs apply. A class can implement many interfaces, but it can extend only one class, so interfaces leave you more room later.
Choose a base class when subclasses really share fields or behavior. In Shape, describe() is written once and each subclass supplies only area(). The cost is coupling. Subclasses depend on the parent's internals, and a class must be declared virtual or abstract before anyone can extend it.
The two can be combined. An interface defines the contract, and an abstract class implements the common part of it.
public interface Notifier {
void send(String message);
}
public abstract class BaseNotifier implements Notifier {
protected String format(String message) {
return '[' + Datetime.now().format() + '] ' + message;
}
public abstract void send(String message);
}
public class DebugNotifier extends BaseNotifier {
public override void send(String message) {
System.debug(format(message));
}
}Callers hold a Notifier. Subclasses reuse format.
Common mistakes
- Using a static variable to hold data that belongs to one object. Every object then shares and overwrites it.
- Building a deep inheritance chain to share a few lines. A small static helper is simpler.
- Creating an interface with only one implementation and no plan for another. Add it when a second implementation or a test substitute appears.
- Forgetting that a
Comparableor other system interface is a contract too. Implement all of its methods.
Exercise
You are writing a service that calculates shipping cost. Three carriers calculate it differently, share no code, and a test must be able to replace the carrier. Which construct do you choose, and why not a static method?
Show answer
Define an interface such as ShippingCalculator with a calculate(Order o) method and implement it once per carrier. A static method ties callers to one class name, so neither a different carrier nor a test double can be substituted. A base class is unnecessary because the carriers share no code.
Exercise
A class keeps a private static Decimal runningTotal and each new object adds its amount to it. Each object is then expected to report its own total. What is wrong, and how do you fix it?
Show answer
The static variable is shared by all objects in the transaction, so every object sees the same total. Make runningTotal an instance variable so each object has its own copy. Keep a static variable only for something that is truly shared, such as an instance counter.