Development Best Practices
  • Home
  • Clean Code
  • Apex
    • Naming Conventions
    • Triggers
    • Unit Testing
    • Principles
      • KISS
      • DRY
      • Single Responsibility
      • Open/Closed
      • YAGNI
    • Patterns
    • SOQL
    • Exception Handling
    • Magic Strings
  • Lightning Components
    • Aura
    • LWC
  • Automation
    • Process Builder
  • Salesforce DX and VSCode
  • Git Source Control
    • Install Git
    • Using Git
    • Development Workflow
      • The Rules
    • Feature Branch Workflow
Powered by GitBook
On this page
  • Avoid hard-coded Strings
  • Best practice
  1. Apex

Magic Strings

Magic strings are String values that are specified directly within application code that have an impact on the application’s behaviour. Frequently, such strings will end up being duplicated within the code.

Avoid hard-coded Strings

// bad 

function Boolean isClosed(Opportunity deal) {
    if (deal.StageName == 'Closed') {
        return true;
    }
    return false;
}

Best practice

Create a class which contains all the String values for a given pick list

public class OpportunityStageNames {
    public static final String New_x = 'New';
    public static final String Discovery = 'Discovery';
    public static final String Proposal = 'Proposal';
    public static final String Closed = 'Closed';
}

And then used this class to access the single instance of the String value.

// good

function Boolean isClosed(Opportunity deal) {
    if (deal.StageName == OpportunityStageNames.Closed) {
        return true;
    }
    return false;
}
PreviousException HandlingNextLightning Components

Last updated 5 years ago