Cache with getters and setters
How to cache data with getters and setters in Apex?
Static data such as object metadata or user profiles Sets and Maps Results of SOQL queries Results of API callouts
Getters and Setters can be great tools for caching data in Apex.
What can be cached?
Static data such as object metadata or user profiles Sets and Maps Results of SOQL queries Results of API callouts
While you can always use Platform Cache, for simple use cases getters and setters may be more suitable.
Let’s check an example
Sometimes the information provided by the UserInfo class is not sufficient. You can easily add more information and cache it so that only one SOQL query will be executed.
public with sharing class CurrentUserInfo {
public static User cachedUserDetails {
get {
if (cachedUserDetails == null) {
cachedUserDetails = [
SELECT Id, Name, FederationIdentifier, ProfileId, UserType, AccountId
FROM User
WHERE Id = :UserInfo.getUserId()
];
}
return cachedUserDetails;
}
private set;
}
public static String getFederationIdentifier() {
return cachedUserDetails.FederationIdentifier;
}
public static String getAccountId() {
return cachedUserDetails.AccountId;
}
}

