Callable Interface in Salesforce

The System.Callable interface enables you to use a common interface to build loosely coupled integrations between Apex classes or triggers, even for code in separate packages. Agreeing upon a common interface enables developers from different companies or different departments to build upon one another’s solutions. Implement this interface to enable the broader community, which might have different solutions than the ones you had in mind, to extend your code’s functionality.

Sample Code:

public class SampleCallable implements System.Callable {
    
    String addPrefix(String str) {
        
        return 'Testing ' + str;
        
    }
    
    String addSuffix(String str) {
        
        return str + ' Testing';
        
    }
 
    public Object call( String action, Map < String, Object > args ) {
        
        switch on action {
            
            when 'prefix' {
                
                return addPrefix(String.valueOf(args.get('strValue')));
                
            }
            when 'suffix' {
                
                return addSuffix(String.valueOf(args.get('strValue')));
                
            }
            when else {
                
                return null;
                
            }
            
        }
        
    }
        
}

Test Class for Callable Interface:

@isTest
private class SampleCallableTest {
 
    static testMethod void testCallable () {
        
        Callable extension = (Callable) Type.forName('SampleCallable').newInstance();
        
        String strPrefix = String.valueOf(extension.call('prefix', new Map < String, Object > {'strValue' => 'Sample'}));
        system.assertEquals('Testing Sample', strPrefix);
        String strSuffix = String.valueOf(extension.call('suffix', new Map < String, Object > {'strValue' => 'Sample'}));
        system.assertEquals('Sample Testing', strSuffix);
        
    }
    
}

Leave a Reply