Sub topic 7
Building configuration-driven logic
This chapter assumes you can write Apex classes and SOQL, you know how to define a custom metadata type and create its records in Setup, and you have read records with getInstance(), getAll(), and SOQL. Here you use those reads to move decisions out of your code and into records.
The idea
A configuration-driven design keeps the rules in custom metadata records and keeps the Apex code generic. The code asks "what does the configuration say?" and acts on the answer. Changing behavior then means editing or deploying a record, not rewriting and redeploying a class.
Three patterns cover most cases:
| Pattern | What a record holds | Best read with |
|---|---|---|
| Feature flag | A name and an on/off value | `getInstance()` |
| Rule table | Thresholds and results | SOQL with `WHERE` and `ORDER BY` |
| Strategy selection | The name of an Apex class | `getInstance()` |
Pattern 1: Feature flags
A flag type such as Feature_Flag__mdt has a checkbox field Is_Enabled__c. Each record's developer name is the flag name. Wrap the lookup in one class so callers never touch the metadata directly.
public with sharing class FeatureFlags {
public static Boolean isEnabled(String flagName) {
Feature_Flag__mdt flag = Feature_Flag__mdt.getInstance(flagName);
return flag != null && flag.Is_Enabled__c;
}
}getInstance() returns null when no record has that developer name. The method above treats a missing flag as disabled, which is the safe default for a new feature.
Callers then branch on the flag:
if (FeatureFlags.isEnabled('New_Checkout')) {
// new behavior
} else {
// existing behavior
}Pattern 2: Rule tables
Use a rule table when the configuration is a list that you filter or sort. getInstance() and getAll() cannot filter or sort, so use SOQL. This example picks the largest discount tier that an order qualifies for.
List<Discount_Rule__mdt> rules = [
SELECT DeveloperName, Min_Amount__c, Percent__c
FROM Discount_Rule__mdt
WHERE Is_Active__c = true
ORDER BY Min_Amount__c DESC
];
Decimal percent = 0;
Decimal orderTotal = 250;
for (Discount_Rule__mdt rule : rules) {
if (orderTotal >= rule.Min_Amount__c) {
percent = rule.Percent__c;
break;
}
}Because the rules are sorted from the highest minimum down, the first match is the best tier. Adding a new tier means adding a record, and the loop does not change. Setting Is_Active__c to false retires a tier without deleting it.
Pattern 3: Strategy selection
When different cases need different logic, define an interface and let a record name the class to use. The Apex code below looks up the record by region code and creates the class named in Class_Name__c.
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);
}
}To support a new region, write a class that implements TaxCalculator and add a record that points to it. TaxService stays untouched. The two checks matter: a missing record and a misspelled class name both fail with a clear message instead of a null pointer error.
Common mistakes
- Reading a record that might not exist without a null check. Decide what a missing record means and handle it.
- Querying with SOQL inside a loop. Read the configuration once before the loop.
- Putting too much logic in records. Records should hold values and names, not scripts.
Exercises
Exercise
In the discount example, why does the SOQL query use ORDER BY MinAmount_c DESC, and what would go wrong with ASC?
Show answer
The loop stops at the first rule the order total qualifies for. With DESC order, that first match is the highest qualifying tier. With ASC order, the lowest tier would match first, so the order would always get the smallest discount it qualifies for.
Exercise
A teammate adds a TaxStrategymdt record for region "CA" but mistypes the class name in ClassName__c. What does TaxService do, and why?
Show answer
Type.forName returns null for a class that does not exist, so TaxService throws an IllegalArgumentException with the message "Unknown class" followed by the bad name. The explicit null check produces this clear error instead of a NullPointerException on newInstance.