1

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;
        }
    }
3
  • 1
    cache.containsKey() executes cache getter which initializes cache 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. Nov 18, 2018 at 19:36
  • 1
    Also, the query is redundant. You can retrieve Record Types without issuing any query nowadays through schema :) salesforce-opensource-library.com/classes/apex/… Nov 18, 2018 at 19:39
  • 1
    Note that the two methods called RecordTypeCache.get() aren't getters. They're just normal methods that happen to be called get. Getters can't be overloaded because they do not take parameters.
    – David Reed
    Nov 18, 2018 at 19:39

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.