Skip to content
Home » Blog Archive » Beginner’s Guide to Salesforce Apex: Understanding Enumerators

Beginner’s Guide to Salesforce Apex: Understanding Enumerators

Hey there, coding crew! I’m back with another blog post in our “Beginner’s Guide to Salesforce Apex” series. In our previous posts, we covered the basics of primitive data types and collections in Apex. Now, we’re ready to dive into the magical world of enumerators. We’ll be breaking down what they are, how to use them, and why they’re super important in Salesforce Apex. So, buckle up, and let’s continue our journey of learning Apex with some easy-to-understand examples and real-world scenarios. 🚀

Introduction to Enumerators

Enumerators, also known as enums, are a powerful feature in Salesforce Apex that allow you to define a collection of named constants.

Enums are useful when you have a fixed set of values that represent specific states, categories, or types within your application. By using enums, you can make your code more readable, organized, and less prone to errors.

How to Define Enumerators

To define an enumerator, use the enum keyword followed by the enumeration name and a set of named constants enclosed in curly braces:

public enum DaysOfWeek { //DaysOfWeek is the enumerator name
    MONDAY, 
    TUESDAY, 
    WEDNESDAY, 
    THURSDAY, 
    FRIDAY, 
    SATURDAY, 
    SUNDAY
}

In this example, we’ve defined an enum called DaysOfWeek that represents the days of the week. The enum has seven values, each representing a different day of the week.

Using Enumerators in Apex

Now that we’ve got the basics down, let’s explore how to use enums in your Apex code. Enums in Apex can be used in various ways, like assigning values to variables, using them in switch statements, or even looping through them.

Using enumerators to assign values to variables

In this example, we’re assigning the value of the FRIDAY literal to a variable called today.

//FRIDAY is one of the value pre-defined in the enumerator. 
//You can use any of the pre-defined value ONLY
DaysOfWeek today = DaysOfWeek.FRIDAY;
system.debug('Check today Value: '+today);
Screenshot of the Developer Console output demonstrating the usage of Enumerator to assign value to variable.

Notes on using enumerators to assign values to variables

When using an Enumerator variable, you cannot assign a value to it that is not included in the predefined set of values. If you try to do so you will get a similar error message as below :

//DaysOfWeek doesn't have TestDayName value
DaysOfWeek today = DaysOfWeek.TestDayName; 
system.debug('Check today Value: '+today);
Screenshot for the Developer Console Error Message

If you try to assign another data type value directly to an Enumerator variable as String for example you will get the below error:

//trying to assign directly a string value
DaysOfWeek today = 'Invalid_Day_Name'; 
system.debug('Check today Value: '+today);
Screenshot for the Developer Console Error Message

Using enumerators in switch statements

Enums work great with switch statements. Take a look at this example:

DaysOfWeek today = DaysOfWeek.FRIDAY;
switch on today {
    when MONDAY{
        System.debug('It\'s Monday');
    }
    when TUESDAY{
        System.debug('It\'s Tuesday');
    }
    when WEDNESDAY{
        System.debug('It\'s Wednesday');
    }
    when THURSDAY{
        System.debug('It\'s Thursday');
    }
    when FRIDAY{
        System.debug('It\'s Friday');
    }
    when SATURDAY{
        System.debug('It\'s Saturday');
    }
    when SUNDAY{
        System.debug('It\'s Sunday');
    }
    when else{
        System.debug('Invalid day of the week');
    }
}

In this example, we’ve declared a DaysOfWeek variable named today and initialized it to DaysOfWeek.FRIDAY. We then use a switch statement to check the value of today and print a message indicating which day it is.

Screenshot of the Developer Console output demonstrating the usage of Enumerator in switch case.

Notes on using enumerators with switch statements

  1. The switch on expression in a switch statement must match the type of the enum: In our previous example we used today which is of type “DaysOfWeek
  2. You cannot have any value in a when clause that is outside of the defined enum values: In our previous example we used “Monday”, “TUESDAY”, etc… If you use a value from outside the enum values as “TestDayName”, you would get the below error in developer console:
switch on today {
    when TestDayName{
        System.debug('It\'s Monday');
    }
    when TUESDAY{
        System.debug('It\'s Tuesday');
    }
    when WEDNESDAY{
Screenshot from Developer console for the invalid Enumerator Value in the Switch Case.
Screenshot for the Developer Console Error Message

Looping through enums

You can also use the values() method of the enum class to get an array of all the possible values and you can loop them using for loop as the below example:

for (DaysOfWeek dayValue : DaysOfWeek.values()) {
    System.debug('Check Day Name : '+ dayValue);
}

In this example, we’re using the values() method of the DaysOfWeek enum to get an array of all the defined values in the enum. We’re then using a for loop to iterate over each value in the array, and printing the value of each day using System.debug().

When we run this code, the output in the Developer Console would be:

Screenshot from the Developer Console to demonstrate how we can loop through the Enumerator values and print them,

Why Enumerators are Important

By now, you might be wondering why enumerators are such a big deal in Salesforce Apex. Here are a few reasons why:

1. Type-safety:

  • Enums provide type safety by ensuring that only valid values can be assigned to variables or passed as arguments to methods or used in Switch Cases.
  • For Example: When we tried to use an invalid enum value in the switch case, we got an error message running the code in developer console.
  • Another Example: When we tried to use an invalid enum value while assigning variable value, we got an error message running the code in developer console.

2. Maintainability

  • Enumerators make it easier to maintain your code by centralizing the definition of constant values.
  • If you need to add a new value to an enum, you can do so in one place and it will be automatically available throughout your code.
  • This reduces the risk of errors caused by duplicate or inconsistent values.

3. Code Organization

Using enumerators in your code can help with code organization by grouping related constants together making your code more maintainable and easier to read.

4. Code Readability

Enums help make your code more readable by providing meaningful names for constant values. For example:

  • In some cases, you may be dealing with an external system that uses its own values to represent object status as [0,1,2], and you may not be able to control those values. In this case, it’s still a good idea to use an enum with meaningful names in your Apex code to make it more readable and self-documenting.
  • To map the values from the external system to your enum, you can create a mapping between the external values and the corresponding enum values. For example, let’s say the external system uses values of 0, 1, and 2 to represent the status of an object, and you want to map these to the ObjectStatus enum with values of ACTIVE, INACTIVE, and DELETED. You could create a mapping like this:
public enum ObjectStatus {
    ACTIVE,
    INACTIVE,
    DELETED
}

public static ObjectStatus mapExternalStatus(Integer externalStatus) {
    Map<Integer, ObjectStatus> statusMap = new Map<Integer, ObjectStatus>{
        0 => ObjectStatus.ACTIVE,
        1 => ObjectStatus.INACTIVE,
        2 => ObjectStatus.DELETED
    };
    return statusMap.get(externalStatus);
}

In this example, we’ve created a static method called mapExternalStatus that takes an Integer parameter representing the external status value. The method uses a Map to map the external values to the corresponding enum values, and returns the mapped value.

To use this method, you would first retrieve the status value from the external system, and then call mapExternalStatus to map it to the corresponding enum value. For example:

// Assume externalStatusValue is retrieved from the external system
Integer externalStatusValue = 1;

ObjectStatus status = mapExternalStatus(externalStatusValue);
if (status == ObjectStatus.ACTIVE) {
    // Do something if the object is active
    System.debug('ACTIVE!!');
} else if (status == ObjectStatus.INACTIVE) {
    // Do something if the object is inactive
    System.debug('INACTIVE!!');
} else if (status == ObjectStatus.DELETED) {
    // Do something if the object is deleted
    System.debug('DELETED!!');
}
Screenshot for the developer console output the Mapping external system value to a readable enumerator value example.
Developer console output printed Inactive because we assumed external system value was 1 and that is mapped to Inactive status

Predefined Salesforce Enumerators

Salesforce provides several predefined Enumerators that you can use in your Apex code. These Enumerators are designed to make it easier to work with common values in Salesforce, such as record types and user roles values.

Let’s explore the following examples:

1. TriggerOperation Enum

TriggerOperation Enumerators are used in Apex triggers to determine the type of DML operation that is being performed on a record. These Enumerators can be useful in writing custom logic for different types of DML operations, such as before insert, after insert, before update, after update, before delete, after delete, before undelete, and after undelete.

One way to use the TriggerOperation Enumerators is by creating a switch case statement that evaluates the Trigger.operationType property. This allows you to call the appropriate trigger handler operation for the specific DML operation that is being performed on the record, whether it’s a before insert, after insert, before update, after update, before delete, after delete, before undelete, or after undelete operation.

trigger AccountTrigger on Account (after insert, after update) {

    switch on Trigger.operationType{
        when AFTER_INSERT{
            //do after insert stuff
        }
        when AFTER_UPDATE{
            //Do after update stuff
        } 

    }
}

2. System.RoundingMode

System.RoundingMode is an Enumerator in Salesforce Apex that represents different rounding modes for decimal numbers. Decimal values in Apex can be rounded up, down, or to the nearest value based on the specified rounding mode.

Check the resources to explore all the different possible values for this enumerator.

Decimal value = 0.5;
Decimal halfUp = value.setScale(0, System.RoundingMode.HALF_UP);
Decimal halfDown = value.setScale(0, System.RoundingMode.HALF_DOWN);

System.debug('Original value: ' + value); // Output: Original value: 0.5
System.debug('HALF_UP value: ' + halfUp); // Output: HALF_UP value: 1
System.debug('HALF_DOWN value: ' + halfDown); // Output: HALF_DOWN value: 0
Developer Console Output

Enumerator Methods

1. values Method

The values() method is used to get an array of all the Enumerator values in the order they were declared.

enum FruitType {
    APPLE,
    BANANA,
    ORANGE,
    PINEAPPLE
}

System.debug(FruitType.values()); 
Developer Console Output for Enum Values() Method

This method can be used to loop through all the possible values of an Enumerator to perform some action, such as building a custom picklist values for a custom LWC or Visualforce page.

2. valueOf(string enumStr) Method

This method is used to convert a string to an Enumerator value.

public enum Fruit {APPLE,BANANA,ORANGE}
Fruit fruitEnum = Fruit.valueOf('banana');
System.debug('Check Enum : '+fruitEnum); 
Developer Console Output for Enum valueOf() Method

The valueOf() method can be useful in a variety of scenarios where you need to convert a string to an Enumerator value. For example, if you are accepting user input for an Enumerator value, you can use the valueOf() method to validate that the input is a valid Enumerator value.

public enum Fruit {APPLE,BANANA,ORANGE}
Fruit fruitEnum = Fruit.valueOf('watermelon');
System.debug('Check Enum : '+fruitEnum); 
Screenshot for the Developer Console Error Message

3. name Method

Returns the name of the Enumerator value as a string.

enum DaysOfWeek {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}

DaysOfWeek today = DaysOfWeek.SATURDAY;
String dayName = today.name(); // Returns "SATURDAY"
System.debug('Day Name Text Value: '+dayName);
Developer Console Output for Enum name() Method

This method can be useful in a variety of scenarios where you need to work with the name of an Enumerator value, such as displaying Enumerator values in a user interface:

  • When building a custom user interface that includes an input field or picklist that is based on an Enumerator, you can use the name() method to get the name of each Enumerator value and display it to the user.
  • For example, if you have an Enumerator for different types of fruit, you could use the name() method to display the name of each fruit in a picklist.

4. ordinal Method

Returns the position of the Enumerator value within the list of values, starting at zero.

enum Months {
    JANUARY,
    FEBRUARY,
    MARCH,
    APRIL,
    MAY,
    JUNE,
    JULY,
    AUGUST,
    SEPTEMBER,
    OCTOBER,
    NOVEMBER,
    DECEMBER
}

Months currentMonth = Months.JUNE;
Integer monthNumber = currentMonth.ordinal(); // Returns 5
System.debug('check monthNumber: '+monthNumber);
Developer Console Output for Enum ordinal() Method

This method can be useful in a variety of scenarios as:

  1. Sorting Enumerator values: If you have a list of values that are based on an Enumerator and you need to sort them based on their position, you can use the ordinal() method to compare the positions of each value and sort them accordingly.
  2. Performing calculations based on the position of a value: If the position of an Enumerator value has a specific meaning or significance, you can use the ordinal() method to perform calculations based on that position.

Conclusion

As you can see, enumerators (enums) are a powerful tool that can help improve your code’s readability, maintainability, and type-safety. I hope this blog post has given you a better understanding of what enumerators are, how to use them, and why they’re important.

Don’t forget to practice using enums in your own Salesforce Apex projects, and keep exploring new ways to make your code even better. Stay tuned for more exciting topics in my “Beginner’s Guide to Salesforce Apex” series. Happy coding! 🚀

Resources

  1. Enums Apex Developer Guide
  2. Enum Methods
  3. TriggerOperation Enum
  4. Rounding Mode

Join the conversation

Your email address will not be published. Required fields are marked *