I've a little confused by the order of execution in the following very useful class from Adrian Larson. If I call "get" with just an SObjectType, invoking the first method, the cache.containsKey(key)
conditional is always true, never returning an empty map. What seems to be happening is that the cache property is created at the moment the first get
is invoked, before the method body is entered. I checked the documentation for Apex properties but didn't find an example of getter overloading. Any tips on how to read this example correctly or on what I'm missing in my understanding of it would be appreciated (from How to get the list of record type Id of an sObject by SOQL).
public with sharing class RecordTypeCache
{
public static Map<String, RecordType> get(SObjectType key)
{
return cache.containsKey(key) ? cache.get(key) : new Map<String, RecordType>();
}
public static RecordType get(SObjectType key, String developerName)
{
return get(key).get(developerName);
}
static Map<SObjectType, Map<String, RecordType>> cache
{
get
{
if (cache == null)
{
cache = new Map<SObjectType, Map<String, RecordType>>();
Map<String, SObjectType> objects = Schema.getGlobalDescribe();
for (RecordType recordType : [SELECT DeveloperName, SObjectType FROM RecordType])
{
SObjectType schemaType = objects.get(recordType.SObjectType);
if (!cache.containsKey(schemaType))
cache.put(schemaType, new Map<String, RecordType>());
cache.get(schemaType).put(recordType.DeveloperName, recordType);
}
}
return cache;
}
private set;
}
}
cache.containsKey()
executescache
getter which initializescache
variable (thus changing it form null to map). Then map is populated with all Record Types in the org. After this,containsKey
is executed. Try running get() on SObject that does not have Record types to see containsKey return false.RecordTypeCache.get()
aren't getters. They're just normal methods that happen to be calledget
. Getters can't be overloaded because they do not take parameters.