How can I design a utility class for handling the common data processing task?

267    Asked by Chandralekhadebbie in Salesforce , Asked on Feb 6, 2024

I am currently tasked with optimization of the performance of a particular complex Salesforce application by using the apex utility classes. How can I design a utility class for handling the common data processing task effectively to gain better code organization and reusability?

 In the context of Salesforce, you can create a utility class in Apex for handling the common data processing task by using the following example which is given below:-


Public class DataUtility {
    // Method to calculate the average of a list of numbers
    Public static Decimal calculateAverage(List numbers) {
        If (numbers.isEmpty()) {
            Return 0;
        }
        Decimal sum = 0;
        For (Integer num : numbers) {
            Sum += num;
        }
        Return sum / numbers.size();
    }
    // Method to filter a list based on a specified condition
    Public static List filterList(List inputList, String condition) {
        List filteredList = new List();
        For (String item : inputList) {
            If (item.contains(condition)) {
                filteredList.add(item);
            }
        }
        Return filteredList;
    }
    // Additional utility methods can be added as needed
}

In this particular example, the class of “DataUtility” would include two methods- one for calculating the average of numbers and the second one is filtering out of a list based on the conditions specified. These methods would be called from even other classes which would help you in gaining reusing of code and organization.

If you want to utilize the utility method in another class, then you can do something like this:-

List numbers = new List{1, 2, 3, 4, 5};

Decimal average = DataUtility.calculateAverage(numbers);

List fruits = new List{‘Apple’, ‘Banana’, ‘Orange’, ‘Grapes’};

List filteredFruits = DataUtility.filterList(fruits, ‘an’);

// Now ‘average’ holds the calculated average, and ‘filteredFruits’ contains fruits containing ‘an’.

This would promote the modular and efficient coding design in Salesforce Apex.



Your Answer

Interviews

Parent Categories