Sub topic 11
Choosing an Apex class from configuration
This chapter covers selecting an Apex class at runtime from a custom metadata record. It assumes you can read custom metadata with getInstance(), define text fields on a custom metadata type, and write basic Apex tests. It builds on the configuration-driven patterns from earlier chapters and on metadata relationship fields.
The problem this solves
Suppose tax rules differ by region. The obvious code is a chain of if or switch branches inside one service class. Every new region means editing that class, retesting it, and deploying it.
A better design keeps the Apex logic behind an interface. Each region gets its own class that implements the interface. A custom metadata record maps a region code to a class name. The service looks up the record, builds the class by name, and calls it. Adding a region means adding a class and a record. The service stays unchanged.
This is the strategy pattern, with the choice of strategy stored as data.
The pieces
You need three things.
- An interface that defines the contract.
- One or more classes that implement it.
- A custom metadata type with a text field holding the class name, plus one record per region.
Define a custom metadata type Tax_Strategy__mdt with a text field Class_Name__c. Create one record per region, where the record's developer name is the region code.
| Label | Developer name | Class_Name__c |
|---|---|---|
| US | US | UsTaxCalculator |
| DE | DE | GermanTaxCalculator |
Developer names must start with a letter and can contain only letters, numbers, and single underscores. A region code like US works. A code like en-US does not, so you would need a mapping or a separate field for such values.
The interface and implementations
public interface TaxCalculator {
Decimal calculate(Decimal amount);
}public with sharing class UsTaxCalculator implements TaxCalculator {
public Decimal calculate(Decimal amount) {
return amount * 0.07;
}
}public with sharing class GermanTaxCalculator implements TaxCalculator {
public Decimal calculate(Decimal amount) {
return amount * 0.19;
}
}Each implementation needs a public or global constructor that takes no arguments. Type.newInstance() calls that constructor. If you declare a constructor with parameters and no no-argument constructor, newInstance() fails at runtime. A class with no explicit constructor has a default one and works.
The service
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 four things in order:
getInstance(regionCode)returns the record, ornullif no record has that developer name.Type.forName(...)converts the class name string into aType. It returnsnullif no such class exists.newInstance()creates an object. It returnsObject, so you cast it to the interface.- The call goes through the interface, so the service never refers to a concrete class.
Both null checks matter. Without them you get a NullPointerException that does not say which region or class name was the problem.
The diagram below shows the flow.
Failure modes
The class name is a string, so the compiler cannot check it. Several things can go wrong at runtime.
- Typo in the record.
Type.forNamereturnsnull. Your explicit check turns this into a readable error. - Class does not implement the interface. The cast throws a
System.TypeException. Catch it if you want to report which class was wrong. - Class has no usable no-argument constructor.
newInstance()throws an exception. - Class is not visible. A class in a managed package must be
globalfor a subscriber org to reference it by name, and the type must be accessible to the calling namespace. - Class was renamed or deleted. Apex does not know the metadata record depends on it. Deployment of the class change succeeds, and the failure appears later when the record is read.
A stricter version catches the cast problem:
public with sharing class SafeTaxService {
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);
}
Object instance = strategyType.newInstance();
if (!(instance instanceof TaxCalculator)) {
throw new IllegalArgumentException(
config.Class_Name__c + ' does not implement TaxCalculator'
);
}
return ((TaxCalculator) instance).calculate(amount);
}
}The instanceof check replaces a TypeException with a message that names the offending class.
Namespaces
Type.forName(String) resolves a name using the namespace of the running code. If the class lives in a managed package, there are two safe options. You can store the fully qualified name, such as acme.UsTaxCalculator. You can also use the two-argument form Type.forName(namespace, className) and keep the namespace in a separate field. Test the lookup in a subscriber org, because a name that resolves in your development org may not resolve once the code is packaged.
Using a relationship field
Instead of a free-text class name you can model the choice with a metadata relationship field, for example a Tax_Strategy__mdt record that points to a Region__mdt record. The relationship makes the link between records validated, because Salesforce checks that the target record exists. It does not validate the class name string. The class name remains text either way.
Testing
You cannot insert custom metadata records in a test, so a test runs against the records that exist in the org. That makes tests fragile if they depend on specific records. There are two common approaches.
The first is to test each implementation directly, without any metadata.
@IsTest
private class TaxCalculatorTest {
@IsTest
static void usCalculatorAppliesSevenPercent() {
TaxCalculator calc = new UsTaxCalculator();
System.assertEquals(7, calc.calculate(100));
}
@IsTest
static void germanCalculatorAppliesNineteenPercent() {
TaxCalculator calc = new GermanTaxCalculator();
System.assertEquals(19, calc.calculate(100));
}
}The second is to make the lookup replaceable so the service test controls which class is used. Split the lookup into a method that a test can override:
public with sharing class TaxService {
@TestVisible
private static Map<String, String> classNameOverrides = new Map<String, String>();
private static String classNameFor(String regionCode) {
if (classNameOverrides.containsKey(regionCode)) {
return classNameOverrides.get(regionCode);
}
Tax_Strategy__mdt config = Tax_Strategy__mdt.getInstance(regionCode);
return config == null ? null : config.Class_Name__c;
}
public static Decimal calculate(String regionCode, Decimal amount) {
String className = classNameFor(regionCode);
if (className == null) {
throw new IllegalArgumentException('No tax strategy for ' + regionCode);
}
Type strategyType = Type.forName(className);
if (strategyType == null) {
throw new IllegalArgumentException('Unknown class ' + className);
}
TaxCalculator calculator = (TaxCalculator) strategyType.newInstance();
return calculator.calculate(amount);
}
}@IsTest
private class TaxServiceTest {
@IsTest
static void usesClassFromOverride() {
TaxService.classNameOverrides.put('TEST', 'UsTaxCalculator');
System.assertEquals(7, TaxService.calculate('TEST', 100));
}
@IsTest
static void unknownClassThrows() {
TaxService.classNameOverrides.put('TEST', 'NoSuchClass');
try {
TaxService.calculate('TEST', 100);
System.assert(false, 'Expected an exception');
} catch (IllegalArgumentException e) {
System.assert(e.getMessage().contains('NoSuchClass'));
}
}
@IsTest
static void missingRegionThrows() {
try {
TaxService.calculate('NOPE', 100);
System.assert(false, 'Expected an exception');
} catch (IllegalArgumentException e) {
System.assert(e.getMessage().contains('NOPE'));
}
}
}One test should also check that every deployed record points at a real class. That test catches renamed or mistyped class names before users do:
@IsTest
private class TaxStrategyConfigTest {
@IsTest
static void everyRecordResolvesToATaxCalculator() {
for (Tax_Strategy__mdt config : Tax_Strategy__mdt.getAll().values()) {
Type t = Type.forName(config.Class_Name__c);
System.assertNotEquals(null, t, 'Missing class ' + config.Class_Name__c);
System.assert(
t.newInstance() instanceof TaxCalculator,
config.Class_Name__c + ' must implement TaxCalculator'
);
}
}
}Design guidelines
- Always put the dynamic part behind an interface. Never cast to a concrete class.
- Fail with messages that name the region and the class.
- Provide a sensible default strategy when it makes sense, instead of throwing for every unknown region.
- Keep strategy classes stateless and cheap to construct, since
newInstance()runs on every call. Cache the instance in a static map if construction is costly. - Use this pattern when the set of behaviors changes over time. For two fixed branches, a plain
ifis simpler and easier to read.
Exercise
A developer adds a new region by creating a TaxStrategymdt record named FR with ClassName__c set to FrenchTaxCalculator, but forgets to deploy the class. What happens when TaxService.calculate('FR', 100) runs, and how can you catch the problem before release?
Show answer
getInstance('FR') returns the record, but Type.forName('FrenchTaxCalculator') returns null, so the service throws IllegalArgumentException with the message "Unknown class FrenchTaxCalculator". To catch it before release, run a test that loops over TaxStrategymdt.getAll().values(), resolves each ClassName__c with Type.forName, and asserts the result is not null and that the instance implements TaxCalculator.
Exercise
Why does a class used with Type.newInstance() need a no-argument constructor, and what does the service gain by casting to TaxCalculator instead of a concrete class?
Show answer
newInstance() takes no arguments, so it can only call a constructor without parameters. If the class declares only a parameterized constructor, the call fails at runtime. Casting to the interface keeps TaxService independent of every concrete class, so new strategies can be added without changing the service.