Apex Singleton design pattern for Schema object to get recordtype Id by name.
1 min readApr 28, 2020
You must have read many articles about using the schema object to get record type id for a given object and record type name instead of using good old SOQL hence reducing number of querys.
But…
That creates a new problem…
Every you need a record id a new Schema object gets initialized in the transaction.
This looks like a perfect place to implement singleton design pattern
Public class utility {
private static Map<String,Schema.SObjectType> schemaInst = null; public static Map<String, Schema.SObjectType> getSchemaInst() {
if (schemaInst == null)
schemaInst = Schema.getGlobalDescribe();
return schemaInst;
}
}
So whenever you want to get recordTypeId by name of a given object…
All you need to do is …
Map<String, Id> recordTypeInfos = new Map<String, Id>();
for(Schema.RecordTypeInfo recType: Utility.getSchemaInstance().get(sObjectAPIName).getDescribe().getRecordTypeInfos()){
if(recType.isActive()){
recordTypeInfos.put(recType.getDeveloperName(), recType.getRecordTypeId());
}
}