Salesforce Dictionary - Free Salesforce GlossarySalesforce Dictionary
Salesforce Developer
medium

How do you implement feature toggles in Apex?

Feature toggles let you enable/disable code paths without redeploying. Patterns:

1. Custom Metadata Type for static toggles:

Create Feature_Flag__mdt with Name and Enabled__c fields. Pre-populate flags in metadata.

`apex public class FeatureFlag { public static Boolean isEnabled(String name) { Feature_Flag__mdt flag = Feature_Flag__mdt.getInstance(name); return flag != null && flag.Enabled__c; } }

// Usage: if (FeatureFlag.isEnabled('NEW_PRICING_ENGINE')) { // new logic } else { // old logic } `

Toggle via metadata deployment. Cached, fast, deployable.

2. Custom Settings (Hierarchy) for runtime toggles:

For toggles that need to flip without a deploy, use Hierarchy Custom Settings. Admin can update via UI.

apex Feature_Toggles__c settings = Feature_Toggles__c.getInstance(UserInfo.getUserId()); if (settings.New_Workflow_Enabled__c) { ... }

Per-user/profile/org overrides; instant. Good for gradual rollouts ("enable for one user, then 10%, then all").

3. Permission Set for code-path access:

Wrap a feature in a Custom Permission. Apex checks FeatureManagement.checkPermission('My_Custom_Perm'). Assign via permission set. Useful for A/B testing or beta features per user.

4. Time-based toggles:

apex if (DateTime.now() >= rolloutDate) { /* new */ } else { /* old */ }

Combined with metadata-stored dates.

5. Geographic / org toggles:

For multi-org or multi-region apps, the toggle reads from Custom Metadata keyed by Region/Org Id.

Best practices:

  • Always have an off path that works correctly. Never assume a flag is always on.
  • Test both paths — coverage required for the legacy code too.
  • Document the deprecation timeline — flags shouldn't live forever.
  • Clean up after rollout — remove old code paths once the new one is stable.
  • Audit access — who can flip a flag in production? Restrict permission.

A common mistake: feature flags pile up indefinitely. Schedule cleanup as part of the rollout plan.

Why this answer works

Senior. The cleanup discipline and the "test both paths" rule are mature signals.

Follow-ups to expect

Related dictionary terms