Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • 10 Salesforce Chrome Extensions to Boost Your Productivity
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Saturday, June 14
    • Home
    • Architecture
    • Salesforce
      • News
      • Apex
      • Integration
      • Books Testimonial
    • Questions
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Integration Posts
    • Downloads
    • About Us
      • Privacy Policy
    SalesforceCodex
    Home»Salesforce»Apex»Best Practices to Avoid Hardcoding in Apex for Cleaner Salesforce Code

    Best Practices to Avoid Hardcoding in Apex for Cleaner Salesforce Code

    Dhanik Lal SahniBy Dhanik Lal SahniOctober 18, 2024Updated:January 15, 2025No Comments4 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Avoid Hardcoding in Apex
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Avoiding hardcoding in Apex is a critical best practice for keeping our code flexible, maintainable, and adaptable to new changes. Hardcoding values, particularly record types, record IDs, profile IDs, and object field names, can have several drawbacks. This post will explain the best practices to avoid hardcoding in Apex for cleaner Salesforce code.

    Drawbacks of Hardcoding in Salesforce Apex

    1. Lack of Flexibility

    Hardcoded values require frequent code changes when business requirements evolve. This will require complete code testing that can increase timelines for new changes. For example, Changing the hardcoded record ID or picklist value demands code updates and testing for existing and new changes.

    2. Environment Dependency

    Due to differences in record type IDs or other settings, hardcoded values may work in one Salesforce environment (e.g., sandbox) but not in another (e.g., production). Test classes will also fail during deployment because the hardcoded ID does not exist in the target Org.

    3. Code Duplication

    If a value is hardcoded in multiple places, updates must be applied in each instance, resulting in redundant effort and an increased risk of errors. This will increase test efforts for new changes as well.

    4. Difficult Testing

    Hardcoded values limit the ability to create reusable and adaptable unit tests because data may differ between environments. This can increase testing efforts for new and existing changes.

    Mitigation Techniques to Avoid Hardcoding

    1. Use custom metadata types
    2. Use custom settings
    3. Custom Labels for User Facing Text
    4. Environment-Specific URLs using Named Credentials

    1. Use custom metadata types

    Custom Metadata Types enable configuration values to be managed declaratively and deployed across environments with values. We can change these values anytime in production as well.

    Custom metadata types | Avoid Hardcoding in Apex | Cleaner Salesforce Code

    The method calculateProductTax calculates tax using a hardcoded tax rate of 0.05. Later, when the tax rate changes, we must change this code. The method calculateTax uses a custom metadata type. We can change the tax rate by changing the value in the FixedTaxRate__c field anytime. This will make our code configurable and maintainable.

    2. Using Custom Setting

    We can also remove hardcoding using Custom Settings in the code. Custom Settings store configurable data for businesses.

    Custom Setting in Salesforce |  Avoid Hardcoding in Apex

    The method calculateTax uses a custom hierarchy setting. We can change the tax rate by changing the value in the FixedTaxRate__c field anytime, making our code configurable and maintainable.

    We can use a Custom Setting or Custom Metadata type to store record type, profile ID, or record ID. This will make our code more configurable and maintainable.

    3. Custom Labels for User Facing Text

    We put the hardcoded text for error messages or alert messages in the code. When the error message or text changes, the code must be changed. To make it configurable, we can store text strings visible to users (e.g., error messages, information, and prompts) in Custom Labels. This makes localization and changes easy without changing code.

    // In your Apex class
    String errorMessage = Label.CustomLabel_TaxInfo_Missing_Error;
    throw new CustomException(errorMessage);

    4. Use Named Credentials for Callouts

    The developer normally puts a hardcoded URL as an API endpoint when we do integration work. This will require code change when we need to change the endpoint URL.

    Rather than hardcoding external API endpoints or credentials, use Named Credentials. These enable you to configure endpoint URLs and authentication data declaratively in Salesforce.

    Check out samples to use named credentials in real-time integration projects.

    Summary

    By avoiding hardcoding and implementing these mitigation strategies, we can ensure that your Salesforce Apex code is more adaptable, maintainable, and scalable. This makes it easier to support and evolve over time in both development and production environments.

    References

    Why You Should Avoid Hard Coding and Three Alternative Solutions

    Related Posts

    • Optimizing Salesforce Apex Code
    • DML or SOQL Inside Loops
    • Limiting data rows for lists
    • Stop Describing every time and use Caching of the described object
    • Use Filter in SOQL
    • Optimize Trigger
    • Bulkify Code
    • Foreign Key Relationship in SOQL
    • Handle Heap Size for Apex Code Optimization

    Other Important Posts

    • How to Integrate Google reCaptcha v3 into the Salesforce Experience Site
    • The Ultimate Checklist for Efficiently Querying Large Data Sets
    • Ultimate Guide to Integrate Stripe with Salesforce CRM
    • How to Seamlessly Integrate Shopify with Salesforce
    • Ultimate Guide to URL Accessibility in LWC

    Need Help?

    If you need help implementing this feature, connect with me on my LinkedIn profile, Dhanik Lal Sahni.

    apex apex code best practice apex code optimization avoid hardcoding in apex custom label custom metadata types custom setting named credential optimize apex code salesforce
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleHow to Remove Customer Details After Refreshing Salesforce Org
    Next Article How to Export Data in Excel with SheetJS in LWC
    Dhanik Lal Sahni
    • Website
    • Facebook
    • X (Twitter)

    With over 18 years of experience in web-based application development, I specialize in Salesforce technology and its ecosystem. My journey has equipped me with expertise in a diverse range of technologies including .NET, .NET Core, MS Dynamics CRM, Azure, Oracle, and SQL Server. I am dedicated to staying at the forefront of technological advancements and continuously researching new developments in the Salesforce realm. My focus remains on leveraging technology to create innovative solutions that drive business success.

    Related Posts

    By Dhanik Lal Sahni9 Mins Read

    10 Salesforce Chrome Extensions to Boost Your Productivity

    June 1, 2025
    By Dhanik Lal Sahni4 Mins Read

    How to Build a Generic Modal Window in Lightning Web Component

    May 26, 2025
    By Dhanik Lal Sahni6 Mins Read

    Top 10 Salesforce Flow Features of Salesforce Summer ’25

    May 11, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • 10 Salesforce Chrome Extensions to Boost Your Productivity
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • Top 20 Salesforce Data Cloud Interview Questions & Answers for Admins June 5, 2025
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    Archives
    Categories
    Tags
    apex (111) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code analysis (3) code optimization (8) custom metadata types (5) design principle (9) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (65) lightning-combobox (5) lightning-datatable (10) lightning component (31) Lightning web component (63) lwc (52) named credential (8) news (4) optimize apex code (4) optimize apex trigger (3) Permission set (4) pmd (3) Queueable (9) rest api (23) S3 Server (4) salesforce (142) salesforce apex (47) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

    Type above and press Enter to search. Press Esc to cancel.

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.