Optimized class to reduce Describe limit in salesforce


/**
*The purpose of this class is to reduce the Describe limits and increasing performance of your app
*author:Sandeep
**/
public class SchemaCache {
private static Map gdMap {get;set;}
private static Map dsrMap = new Map();
private static Map dfrMap = new Map();
private static Map<String, Map> sObjFldMap = new Map<String, Map>();

//Only retrive map of sobjects if not already retrieved
public static Map getGlobalDescribeMap() {
if(gdMap == null) {
gdMap = Schema.getGlobalDescribe();
}
return gdMap;
}

//Describe an object only once otherwise returns already described
public static DescribeSobjectResult getSobjectDescribe(String obj) {
if(!dsrMap.containsKey(obj)) {
dsrMap.put(obj, getGlobalDescribeMap().get(obj).getDescribe());
}
return dsrMap.get(obj);
}

//Return map of sobject obj's field using efficient approach
public static Map getSobjectFieldsMap(String obj) {
if(!sObjFldMap.containsKey(obj)) {
sObjFldMap.put(obj, getSobjectDescribe(obj).fields.getMap());
}
return sObjFldMap.get(obj);
}

//Describe a field of an object only once otherwise returns field already described
public static DescribeFieldResult getFieldDescribe(String obj, String fld) {
if(!dfrMap.containsKey(fld)) {
dfrMap.put(fld, getSobjectDescribe(obj).fields.getMap().get(fld).getDescribe());
}
return dfrMap.get(fld);
}
}

Published by Sandeep Kumar

He is a Salesforce Certified Application Architect having 11+ years of experience in Salesforce.

Leave a Reply