Sub topic 11
Choosing an Apex class from configuration
This chapter assumes you can read custom metadata records with getInstance() and know how to write an Apex interface and a test class. It builds on the configuration-driven patterns from the earlier chapters.
The idea
A common way to choose behavior is an if/else chain on a value such as a region code. Each new region means editing and redeploying that chain. You can avoid this by storing the name of an Apex class in a custom metadata record. Code then loads the class by name at runtime.
The pieces are:
- An interface that defines the behavior.
- One class per variant that implements the interface.
- A custom metadata type with a text field holding the class name.
- A service that reads the record, loads the class, and calls it.
Adding a new variant needs a new class and a new record. The service class stays unchanged.
The service
The type Tax_Strategy__mdt has a text field Class_Name__c. Each record's developer name is a region code, such as US or DE.
public interface TaxCalculator {
Decimal calculate(Decimal amount);
}
public with sharing class TaxService {
public static Decimal calculate(String regionCode, Decimal amount) {
Tax_Strategy__mdt config = Tax_Strategy__mdt.getInstance(regionCode);
if (config == null) {
throw new IllegalArgumentException('No tax strategy for ' + regionCode);
}
Type strategyType = Type.forName(config.Class_Name__c);
if (strategyType == null) {
throw new IllegalArgumentException('Unknown class ' + config.Class_Name__c);
}
TaxCalculator calculator = (TaxCalculator) strategyType.newInstance();
return calculator.calculate(amount);
}
}The method does three separate things:
getInstance()returnsnullwhen no record matches, so the code checks for that first.Type.forName()returnsnullwhen the class does not exist or is not visible to the caller. The code checks this too, and the error message names the bad value.newInstance()creates the object with its no-argument constructor. The cast toTaxCalculatorassumes the class implements the interface.
A matching implementation
public class UsTaxCalculator implements TaxCalculator {
public Decimal calculate(Decimal amount) {
return amount * 0.07;
}
}Create a Tax_Strategy__mdt record with developer name US and Class_Name__c set to UsTaxCalculator. A call to TaxService.calculate('US', 100) then returns 7.00.
Common errors
| Problem | Cause | Fix |
|---|---|---|
| `Type.forName()` returns `null` | Misspelled class name, or the class was not deployed to this org | Validate the name and fail with a clear message |
| `System.TypeException` on the cast | The class does not implement the interface | Check the implementation, or test with `instanceof` before casting |
| `newInstance()` fails | The class has no public no-argument constructor, or it is abstract | Give strategy classes a default constructor |
| Class from a managed package not found | The name needs a namespace prefix | Store the full name, for example `ns.ClassName` |
Trade-offs
Loading by name moves a compile-time check to runtime. A typo in a record does not fail a deployment. It fails when a user hits that code path.
Apex also cannot see that the class is used, so renaming or deleting it will not warn you. Keep strategy classes together and document which type depends on them.
Exercise
A TaxService.calculate('FR', 100) call throws IllegalArgumentException with the message "Unknown class FrTaxCalculator". The FR record exists. What does this tell you, and what do you check?
Show answer
The record was found, because the first null check passed. Type.forName('FrTaxCalculator') returned null. Check that the class exists in this org with exactly that spelling, that it was deployed along with the record, and that it is visible to the calling code. Also check for a missing namespace prefix if the class comes from a package.
Exercise
Why must a strategy class used with Type.forName() and newInstance() have a public no-argument constructor, and what could you do if a strategy needs data?
Show answer
newInstance() cannot pass arguments, so it only works with a no-argument constructor. If the strategy needs data, pass it to the method call, for example by adding parameters to the interface method, or add a setter or init method on the interface that the service calls after creating the object.