Stat Tracker

Monday, December 6, 2010

Salesforce Schema Manager Singleton Pattern

I've been fortunate enough to work on some pretty cool Salesforce projects. One requirement that comes up a lot is to make generic utilities which can run over any set of SObjects. For example, performing things like displaying all the available fields in a Visualforce Page or doing some introspection on objects.

As of Winter 11, they have increased the SObject describe limits from 10 to 100 which is nice. However, this may still not be enough if your making duplicate Describe calls for the same object. However, if you use a Singleton pattern to only retrieve the information one time during a session, you can help reduce making duplicate describe calls, saving you precious describe limits! Below is a simle example where I am caching all the SObject Global Describe into a Map, so that I can quickly access any SObject Type based on the API name of the custom object.


//This class will do all the methods to retrieve schema infomraiton on SObject for apex
//This will ensure that multiple calls to descibes aren't called so we don't hit gov limits
public with sharing class SchemaManager
    private static Map<String, Schema.SObjectType> sobjectSchemaMap;
    //Retrieve the specific Schema.SobjectType for a object so we can inspect it
    public static Schema.SObjectType getObjectSchema(String objectAPIName)
        if(sobjectSchemaMap == null)
            sobjectSchemaMap = Schema.getGlobalDescribe();
        Schema.SObjectType aSObjectType = sobjectSchemaMap.get(objectAPIName);
        return aSobjectType;

I have used this pattern many times, and have expanded on it for caching field metadata describes as well. I didn't post the larger Schema Manager here, but you get the idea.