Learning can be easy ..

Understanding Enums in Salesforce Apex – Quick Glance

Introduction

Enums, or enumerations, play a crucial role in Salesforce Apex development by allowing developers to define a set of named constants. Let’s take a quick look at some code samples to review as to how and when to use enums in Apex Salesforce.

Key Takeaways

  • Enums in Salesforce Apex provide a powerful way to ensure data integrity and consistency by restricting variables to predefined constant values.
  • Using Enums enhances code readability, reduces errors, and facilitates better code management.
  • Enum methods like values(), valueOf(), name(), and ordinal() offer various functionalities for interacting with Enums and other data types.

Details

What are Enums in Salesforce Apex?

Enums in Salesforce Apex are user-defined data types that define a fixed set of named constants. They are used to create a collection of related values, making code more readable, manageable, and consistent.

Why Use Enums in Salesforce Apex?

Enums are valuable in scenarios where variables should be restricted to specific values, such as status management, configuration settings, command patterns, filtering options, role or permission management, custom setting values, and workflow or process steps. They ensure type safety, improve code readability, and simplify maintenance.

When to Use Enums in Salesforce Apex?

  • Status Management: Representing stages in a process.
  • Configuration Settings: Defining predefined configuration options.
  • Filtering Options: Representing data filtering options.
  • Role or Permission Management: Defining user roles or permissions.
  • Custom Metadata / Custom Setting Values: Encapsulating predefined values for custom metadata or custom settings.
  • Process Steps: Managing transitions between distinct steps.

Best Practices

  • Use clear and concise names for Enums reflecting their purpose.
  • Organize Enums logically by grouping related constants together.
  • When modifying an existing Enum, create a new version for compatibility.
  • Avoid unnecessary default getters and setters unless required for Visualforce attributes.
  • Ensure Enum values are descriptive and meaningful for better understanding.

Summary

  • Enums in Salesforce Apex provide a structured way to define a fixed set of named constants, ensuring code consistency and readability.
  • By following best practices and leveraging Enum methods, developers can enhance data integrity, streamline development processes, and improve overall code quality.

Code Samples

//_________________________________________
//1.	Defining an Enum in Apex:
public enum Status{
    Active,
    Inactive
}

// Defining an Enum in Apex:
public enum DaysOfWeek {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

//_________________________________________
//2.	Using enums in Salesforce Apex class
public class OrderStatus {
    public enum Status {
        NEW, PENDING, SHIPPED, DELIVERED, CANCELLED
    }

    public Status getStatus() {
        return Status.NEW;
    }
}

//_________________________________________
//3.	Using Enum in a Switch Case Statement:
Status currentStatus = Status.Active;
switch on currentStatus {
    when Active {
        System.debug('Status is Active');
    }
    when Inactive {
        System.debug('Status is Inactive');
    }
    when else {
        System.debug('Unknown status');
    }
}

//_________________________________________
//   Handling Unknown Enum Types in Switch Case:
Type selectedType = getType();
switch on selectedType {
    when A{
        // Do something for type A
    }
    when B{
        // Do something for type B
    }
    when C{
        // Do something for type C
    }
    when else {
        throw new CustomException('Unknown type: ' + selectedType);
    }
}

//_________________________________________
//4.	Iterating over Enum Values:
for(Status s : Status.values()){
    System.debug(s.name());
}

//_________________________________________
//5.	Creating a Map with Enum as Keys:
Map<Status, String> statusMap = new Map<Status, String>{
    Status.Active => 'Active',
    Status.Inactive => 'Inactive'
};

//_________________________________________
//6.	Passing Enum Value from Lightning Controller to Apex:
@AuraEnabled
public static void processStatus(String status){
    Status selectedStatus = Status.valueOf(status);
    // Perform operations based on the selected status
}

//_________________________________________
//7.	Using Enums with Database.Stateful in Batchable Apex:
global class BatchProcess implements Database.Batchable<SObject>, Database.Stateful {
    public Enum Type {A, B, C}
    
    global void execute(Database.BatchableContext BC, List<SObject> scope) {
        Type currentType = Type.A;
        // Perform batch processing based on the current type
    }
}

//_________________________________________
//8.	Using the valueOf() method to convert a string to an enum constant value
String inputString = 'MONDAY';
DaysOfWeek day = DaysOfWeek.valueOf(inputString);
// Enum with static initialization code
public enum MyEnum {
    VALUE1, VALUE2;
    static {
        // Static initialization code here
    }
}

//_________________________________________
//	Converting Enum Values to String Array for Lightning Web Components (LWC):
@AuraEnabled(cacheable=true)
public static String[] getEnumValues() {
    String[] values = new String[]{};
    for(Type t : Type.values()){
        values.add(t.name());
    }
    return values;
}

//_________________________________________
//9.	Limit on the Number of Enum Items:
// Defining an enum with maximum allowed values
public enum Demo{
    A, B, C, D, E, F, G // Add more as needed within the limit
}

//_________________________________________
//10.	Handling Enum Value Increment in Apex:
public Type getNextValue(Type current){
    Integer nextIndex = Math.mod(current.ordinal() + 1, Type.values().size());
    return Type.values()[nextIndex];
}

Please share your ideas on this topic …

This site uses Akismet to reduce spam. Learn how your comment data is processed.