Sub topic 14
Pitfalls and design guidelines
This chapter collects the mistakes that cause the most trouble with custom metadata types, and the design habits that avoid them. It assumes you can already define a type, create records, and read them with getInstance(), getAll(), and SOQL. It also assumes you know how to write a basic @IsTest class and that you have deployed metadata between orgs.
Pitfalls at a glance
| Pitfall | What goes wrong | Guideline |
|---|---|---|
| Hardcoded record names | A renamed or missing record fails silently or crashes | Keep names in one constant or accessor and handle `null` |
| Treating `null` as normal | A missing record is read as "off" or "zero" without anyone noticing | Choose a fail-safe default per setting, and fail loudly where needed |
| Expecting DML | `insert` and `update` on a `__mdt` record do not work | Use the Metadata API for writes, or deploy records |
| Reading right after a write | The deployment is asynchronous, so the old value is still returned | Never depend on the new value in the same transaction |
| Tests tied to org data | Tests pass in one org and fail in another | Add an override seam, as in the testing chapter |
| Unchecked `Type.forName` | `null` results, bad casts, and missing constructors | Validate the type and check `instanceof` |
| Using it for the wrong data | Large or per-user data hits limits or is awkward to manage | Use custom objects or custom settings |
Hardcoded record names
Every getInstance('New_Checkout') call embeds a developer name. That is a contract between code and data. Three failures follow from it:
- Someone deletes or never deploys the record, and
getInstance()returnsnull. - The record exists in a sandbox but was not included in the deployment to production.
- Two classes spell the same name differently, and one is wrong.
Wrap every lookup in one accessor so the name appears in a single place and the null case is handled once. Callers then work with a clear contract and not a raw record.
public with sharing class DiscountConfig {
public class ConfigException extends Exception {}
public static Discount_Rule__mdt requireRule(String devName) {
Discount_Rule__mdt rule = Discount_Rule__mdt.getInstance(devName);
if (rule == null) {
throw new ConfigException('Missing Discount_Rule__mdt record: ' + devName);
}
return rule;
}
}Use a throwing accessor like this when the code cannot work without the record. Use a defaulting accessor, like FeatureFlags.isEnabled(), when absence is a legitimate state.
Choose the default for a missing record
FeatureFlags.isEnabled() treats a missing flag as disabled. That is a good default for a new feature, because a missed deployment leaves the feature off. It is a bad default for a safety switch such as "block payments over the fraud threshold". There, a missing record should stop the process, or the code should fall back to the stricter behavior.
Decide the default for each setting on purpose, and write it down in the accessor. Do not let null decide it.
No DML, and asynchronous writes
You cannot run insert, update, or delete on a custom metadata record. Records are metadata, so you change them by editing them in Setup, deploying them, or enqueueing a Metadata API deployment from Apex.
The Apex route has three further consequences:
Metadata.Operations.enqueueDeployment()returns anIdright away, but the deployment runs later. If you callgetInstance()afterwards in the same transaction, you get the old value.- Success or failure arrives only in the
Metadata.DeployCallback. If you do not implement it carefully, failures go unnoticed. - The running user needs permission to deploy metadata (for example, Customize Application). A user who can run your code may not be allowed to change the setting.
Because of this, do not use custom metadata for values that change on every transaction, such as counters or "last run" timestamps. A custom object or custom setting holds that kind of data.
Tests that depend on the org
Tests cannot create custom metadata records, so a test that calls getInstance('New_Checkout') sees whatever the org contains. It passes in the org where the record exists and fails in a fresh scratch org that lacks it.
The remedy is the override seam from the testing chapter: a @TestVisible static member that production code consults first. Keep the seam small and keep it in one class. A test then sets exactly the values it needs and does not depend on record contents.
Also test the unhappy paths, which are the missing-record path and the invalid-class path. These are the paths that fail in production when a deployment is incomplete.
Dynamic class loading needs guards
The TaxService example uses Type.forName() and a cast. Three things can still go wrong:
Type.forName()returnsnullif the name is misspelled, the class does not exist, or the class is in a namespace you did not include.- The cast
(TaxCalculator) strategyType.newInstance()throws aTypeExceptionif the class does not implement the interface. newInstance()fails if the class has no accessible no-argument constructor.
Check the interface explicitly and report a message that names the bad setting:
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);
}
Object candidate = strategyType.newInstance();
if (!(candidate instanceof TaxCalculator)) {
throw new IllegalArgumentException(
config.Class_Name__c + ' does not implement TaxCalculator'
);
}
return ((TaxCalculator) candidate).calculate(amount);
}
}This version assumes the TaxCalculator interface from the earlier chapter. Add a test that points a record at a class that does not implement it. You can do that by testing the check through a helper that takes the class name as a parameter.
Also remember that renaming or deleting an Apex class does not update the record that names it. The compiler cannot see the string, so the break shows up at run time.
Pick the right tool for the data
Custom metadata is for configuration that developers or admins define once and deploy. It is a poor fit when:
- Records are created by end users or by business processes. Use a custom object.
- Values differ per user or per profile and must be changed at run time without a deployment. Use a hierarchy custom setting.
- Values are secrets such as API keys or passwords. Use named credentials or another secret store. Protected visibility limits who can read a record in a managed package, but it does not make a field a safe place for credentials.
- The data set is large or grows over time. Custom metadata has an org-wide storage limit, and records are heavier to manage than data rows.
Query cost and read patterns
getInstance() and getAll() do not issue SOQL queries, so they do not use up the per-transaction query limit. A SOQL query on a custom metadata type does count as a query. Prefer the get methods when you only need lookups by name or the full set. Reserve SOQL for filtering and sorting, as in the discount-tier example.
Do not call getAll() or run a query inside a loop. Read the configuration once, hold it in a local variable or a static field, and reuse it for the rest of the transaction.
Deployment pitfalls
- A record you edit directly in production is overwritten the next time a deployment includes that record. Make changes in source control and deploy them, or accept that the org copy is temporary.
- Records are only as consistent as your deployment. If a class reads a field that is not deployed yet, the code fails. Deploy the type, fields, and records together with the code that needs them.
- In a managed package, a protected type is invisible to subscriber code. If your code in the subscriber org needs to read it, make the type public.
Design guidelines
- Wrap every custom metadata lookup in one accessor class, and keep developer names out of business logic.
- Decide the missing-record behavior for each setting, and test it.
- Give every type an active flag or similar field if you expect to retire records, and filter on it in SOQL.
- Keep configuration records small and stable. Put per-transaction state elsewhere.
- Validate configuration when you load it, not when you first use it in a rare branch.
- Add a seam for tests in the accessor and use it in every test.
- Document each type, field, and record with its help text and description, so an admin knows what a change does.
- Treat writes through the Metadata API as rare, asynchronous administrative actions.
Exercise
A feature flag class returns false when the record is missing. Name one kind of setting where this default is wrong, and say what the accessor should do instead.
Show answer
A safety or compliance switch, such as "block payments over the fraud limit", is a wrong fit for this default, because a missing record would silently turn the protection off. The accessor should throw an exception, or fall back to the strict behavior, so the missing deployment is noticed.
Exercise
Your code calls Metadata.Operations.enqueueDeployment() to turn on a flag, then calls FeatureFlags.isEnabled('New_Checkout') on the next line and still gets false. Why, and how do you learn whether the change worked?
Show answer
The deployment is asynchronous, so the record has not changed yet when the next line runs, and getInstance() returns the old value. You learn the result in the handleResult method of the Metadata.DeployCallback you passed to enqueueDeployment(), where result.status shows whether the deployment succeeded.
Exercise
A TaxService call fails in production with a TypeException, although the Class_Name__c value names an existing class. What is the likely cause, and what check prevents it?
Show answer
The named class exists but does not implement TaxCalculator, so the cast fails. Test candidate instanceof TaxCalculator after newInstance() and throw an error that names the class and the missing interface.