Apex utility classes help keep your Salesforce code clean, reusable, and efficient. In this blog, we’ll look at two handy Apex utility classes: one for capitalizing the first letter of a string and another for checking if a date is in the future. These examples follow good programming practices, making them easy to reuse across your org.
Formatting text fields like names or titles is a common requirement. This utility method ensures that the first letter is uppercase and the rest are lowercase.
public class StringUtils {
// Capitalizes the first letter of the input string
public static String capitalizeFirst(String input) {
if (String.isBlank(input)) return input;
return input.substring(0,1).toUpperCase() + input.substring(1).toLowerCase();
}
}
Usage Example:
String result = StringUtils.capitalizeFirst('salesforce');
System.debug(result); // Output: Salesforce
Validating that a date is in the future can help with event planning, subscription management, and more.
public class DateUtils {
// Checks if the given date is in the future
public static Boolean isFutureDate(Date inputDate) {
if (inputDate == null) return false;
return inputDate > Date.today();
}
}
Usage Example:
Boolean isFuture = DateUtils.isFutureDate(Date.today().addDays(5));
System.debug(isFuture); // Output: true
- Reusable: Centralizes logic for easy maintenance.
- Efficient: Reduces code duplication and errors.
- Clean: Keeps triggers and controllers focused on business logic.
Happy coding with Apex!
Post a Comment