Using Enums Effectively in Salesforce Apex

Enums in Apex are a great way to define a fixed set of constants, making your code more readable and reducing errors from hardcoded values. Here’s a helpful example that demonstrates how to use enums in Apex for order statuses, user roles, and payment methods.

🧑‍💻 Code Example:

Apex Enum Examples

🔹 Example 1: Order Status Enum

public enum OrderStatus { NEW, PROCESSING, SHIPPED, DELIVERED }

OrderStatus currentStatus = OrderStatus.NEW;

if (currentStatus == OrderStatus.NEW) {
    System.debug('Order just placed!');
}

Useful for tracking order lifecycle stages without relying on strings or integers.


🔹 Example 2: User Role Enum

public enum UserRole { ADMIN, EDITOR, VIEWER }

public String getUserPermissions(UserRole role) {
    switch on role {
        when ADMIN { return 'Full Access'; }
        when EDITOR { return 'Edit Access'; }
        when VIEWER { return 'Read Only'; }
    }
}

A clean and readable way to manage role-based access logic using switch statements introduced in newer Apex versions.


🔹 Example 3: Payment Method Enum

public enum PaymentMethod { CREDIT_CARD, PAYPAL, BANK_TRANSFER }

PaymentMethod selectedPayment = PaymentMethod.PAYPAL;
System.debug('Selected: ' + selectedPayment);

Ideal for representing predefined choices like payment options in a checkout process.


Conclusion:

Using enums in Apex promotes best practices by improving code clarity, preventing invalid values, and simplifying control flow with switch statements. Try incorporating enums in your own org to write more maintainable and scalable Apex code!


This site uses cookies to offer you a better browsing experience. By browsing this website, you agree to our use of cookies.