Saturday, March 21, 2015

Enums in Apex (Salesforce)


Enums in Apex


Apex is probably the first on-demand programming language by Salesforce.com that provides easy, fast and robust ways to design, develop, test and deploy apps on Force.com platform. Apex is more similar to Java but it has some differences which makes it very unique programming language.

Apex also has Enums like we have in Java and other programming languages with some unique differences. 

Let's take an example: We need to send data FROM different objects of Salesforce TO some External 3rd party system.

Below is the code which gives you an idea that how we can use Enums here instead of using variables (e.g. to check the object type).



public class IntegrationImplementation{
    // Declare Enums
    public Enum serviceType {ACCOUNT, CONTACT}
    
    // a method to send Notification based on Object Type
    public static String sendNotification(IntegrationImplementation.serviceType objectType, Set<Id> objectIds){
        String resultCallOutNotification = '';
        // For Account
        if(objectType == serviceType.ACCOUNT){
            // logic here
        }
        // ... logic here for other object types
        return resultCallOutNotification;
    }
}

public class callOutExternalSystem{
    public static void sendAccountToExternalSystem(){
        Set<Id> setAccountIds = new Set<Id>();
        // For Account
        String resultNotification = IntegrationImplementation.sendNotification(IntegrationImplementation.serviceType.ACCOUNT, setAccountIds); 
    }
}

For further details: