Sub topic 7
Building configuration-driven logic
Earlier chapters showed how to define custom metadata types, create records, and read them with getInstance(), getAll(), and SOQL. This chapter covers how to use those records to decide what your Apex does. It assumes you can write Apex classes, read a SOQL query, and have a type such as Feature_Flag__mdt defined in your org.
What "configuration-driven" means
In configuration-driven code, the rules that change often live in records. The code that interprets those rules stays stable. Compare two versions of the same discount logic:
- Hardcoded:
if (total >= 100) percent = 5;sits in a class. Changing the threshold means editing Apex, running tests, and deploying code. - Configuration-driven: The class reads thresholds from
Discount_Rule__mdtrecords. Changing the threshold means editing a record, which an admin can do in Setup and which deploys with the same tools as other metadata.
The aim is not to move all logic into records. You move the values and choices that vary by org, region, or release, and keep the algorithm in code.
Deciding what belongs in configuration
Not every constant should become a record. Ask these questions about each candidate value:
- Does it change more often than the code around it?
- Does it differ between sandbox and production, or between customers or regions?
- Should an admin be able to change it without a developer?
- Is it safe for it to take effect without a code review of the logic that uses it?
If most answers are no, leave it as a constant. Every record adds a dependency that tests, deployments, and documentation must account for.
| Pattern | What the record holds | Typical read method |
|---|---|---|
| Feature flag | A boolean for one named feature | `getInstance()` |
| Threshold or tier table | Several rows of numbers, evaluated in order | SOQL with `ORDER BY` |
| Lookup by key | One row per region, channel, or record type | `getInstance()` |
| Strategy selection | The name of a class to run | `getInstance()` plus `Type.forName()` |
| Full configuration snapshot | All rows at once | `getAll()` |
Pattern 1: feature flags
A feature flag lets you ship code that is switched off, then turn it on later without another deployment. The wrapper below hides the metadata lookup behind one method:
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;
}
}The method makes two design decisions that are worth keeping.
First, a missing record means disabled. getInstance() returns null when no record has that developer name, so the flag != null check prevents a NullPointerException. A flag that was never deployed to an org then behaves as off, which is the safe default for new features.
Second, callers never touch the type directly. If you later change where flags are stored, only FeatureFlags changes. This also gives your tests a single place to override values, which the testing chapter covers.
Calling it looks like this:
public with sharing class CheckoutService {
public static String selectCheckoutPath() {
if (FeatureFlags.isEnabled('New_Checkout')) {
return 'new';
}
return 'legacy';
}
}getInstance() does not run a SOQL query, so calling isEnabled inside a loop does not consume query limits. Still, avoid scattering the flag name as a string literal across many classes. A typo such as 'New_Chekout' silently returns false. Define each name once, as a constant in a small class, and reference the constant.
Pattern 2: rule tables evaluated in order
Some configuration is a list of rules where the first match wins. A discount schedule is a typical case: orders over 100 get 5%, over 500 get 10%, and so on. getInstance() and getAll() cannot filter or sort, so use SOQL:
public with sharing class DiscountService {
private static List<Discount_Rule__mdt> activeRules;
private static List<Discount_Rule__mdt> getActiveRules() {
if (activeRules == null) {
activeRules = [
SELECT DeveloperName, Min_Amount__c, Percent__c
FROM Discount_Rule__mdt
WHERE Is_Active__c = true
ORDER BY Min_Amount__c DESC
];
}
return activeRules;
}
public static Decimal percentFor(Decimal orderTotal) {
if (orderTotal == null) {
return 0;
}
for (Discount_Rule__mdt rule : getActiveRules()) {
if (rule.Min_Amount__c != null && orderTotal >= rule.Min_Amount__c) {
return rule.Percent__c == null ? 0 : rule.Percent__c;
}
}
return 0;
}
}The ORDER BY Min_Amount__c DESC clause puts the largest threshold first. The loop therefore returns the best tier the order qualifies for, and the first match is the correct one. The ordering is what makes return inside the loop safe.
Three details keep this reliable:
- Cache in a static variable. Within one transaction, a trigger may call
percentForfor hundreds of records. The static list means the query runs once per transaction instead of once per call. SOQL on custom metadata still counts toward the per-transaction query limit. - Guard against null fields. A record can exist with an empty
Min_Amount__corPercent__c. Without the checks, the comparison or the return value throws or misbehaves. - Return a defined default. When no rule matches, the method returns
0, notnull. Callers should not need to know how the configuration is shaped.
Pattern 3: lookup by key
When each row describes one case, such as a tax rate per region, name the records after the key and read them with getInstance():
public with sharing class RegionSettings {
public static Decimal handlingFee(String regionCode) {
Region_Config__mdt config = Region_Config__mdt.getInstance(regionCode);
if (config == null || config.Handling_Fee__c == null) {
return 0;
}
return config.Handling_Fee__c;
}
}This works only if the developer name is a stable, meaningful key. getInstance() matches on the developer name, which allows letters, numbers, and underscores, and cannot start with a digit. A region code such as US-CA is not a valid developer name. Either normalize the key (US_CA) or store the real code in a text field and query by it.
Decide deliberately what to do when the key is missing. Returning a default, as above, suits optional behavior. For required behavior, throw an exception with a clear message so the failure is easy to trace:
Region_Config__mdt config = Region_Config__mdt.getInstance(regionCode);
if (config == null) {
throw new IllegalArgumentException('No Region_Config__mdt record named ' + regionCode);
}Pattern 4: strategy selection
A record can also name the behavior to run. The chapter on choosing an Apex class from configuration covers Type.forName() in detail. The idea in brief: a text field holds the name of a class that implements an interface, and a dispatcher instantiates it. Adding support for a new region then means writing one new class and creating one new record. The dispatcher does not change.
Use this pattern when behavior, not just a number, varies by configuration. Do not use it for a choice between two fixed branches. An if statement and a flag are simpler and easier to debug.
How the pieces fit together
Choosing the read method
The choice follows from what the logic needs:
- Use
getInstance()when you know the developer name. It is the cheapest option and uses no SOQL query. - Use
getAll()when you need every record, for example to build a map of all flags once. The result is keyed by developer name, and you should not depend on any iteration order. - Use SOQL when you need to filter on a field, sort, or select a subset. Remember that
ORDER BYon a rule table is part of the logic. If someone removes it, results change.
Design guidelines for configuration-driven code
- Wrap reads in one class per concern.
FeatureFlags,DiscountService, andRegionSettingsgive you a single point to cache, validate, and override in tests. - Treat missing and incomplete records as normal. A record may be absent in a new sandbox or have blank fields after a partial deployment. Decide each default explicitly.
- Keep records data, not code. If a record needs a long script to be understood, the configuration is acting as a programming language. Move that logic back into Apex.
- Name records for what they mean. Developer names become part of your code's contract. Renaming
New_Checkoutbreaks every caller that uses the old string, and the compiler will not warn you. - Remove dead configuration. When a flag has been on in production for months, delete the flag and the
if, not just the record.
Exercise
A Shipping_Rule__mdt type has fields Min_Weight__c and Cost__c. You want a method that returns the cost for the heaviest weight band the package qualifies for, and 0 if no band applies. Which read method do you use, what clause is essential in the query, and why should the rules be cached in a static variable?
Show answer
Use SOQL, because you must sort and compare fields, which getInstance() and getAll() cannot do. Include ORDER BY MinWeightc DESC so the first rule whose MinWeight__c is less than or equal to the package weight is the heaviest qualifying band. Cache the query result in a static List so the query runs once per transaction even when the method is called for many records, because SOQL on custom metadata still counts toward the query limit. Also check for null fields and return 0 when nothing matches.