How to populate Map only if Map is Empty

  • I am trying to create a Map of Account Record Types that any method in my class can reference and only the first call will need to populate it. Since it's populated by a SOQL query, I want to limit that necessity to only once.

    I'm attempting to do this with a getter, but I'm not committed to that if there is a better design.

    When I attempt the following in Execute Anonymous, it throws "System.NullPointerException: Attempt to de-reference a null object" for the accountRecordTypes.isEmpty().

    public static Map<String, String> accountRecordTypes {
            get {
                if (accountRecordTypes.isEmpty()){
                    accountRecordTypes = new Map<String, String>();
                    //Create a map between the Record Type Name and Id for easy retrieval in both Sandbox and Production
                    List<RecordType> rtypes = [Select Name, Id From RecordType where sObjectType='Account' and isActive=true];
                    for(RecordType rt: rtypes) accountRecordTypes.put(rt.Name,rt.Id);
                return accountRecordTypes;
  • You need to add a null check to your guard condition.

     if (accountRecordTypes == null || accountRecordTypes.isEmpty()) {

    The corresponding member that automagically exists behind the property won't be initialised until you call accountRecordTypes = new Map<String, String>();. So the original call to .isEmpty() would have been on null.

    As Jesse Altman commented, the null check alone is probably preferable here. If there are no RecordType records that match the SOQL query you don't want to be running the query code again every time the property is called.

    Beat me to it by a few seconds, but this is the right answer. You are calling isEmpty on an instance that has never been instantiated. I would also go as far as removing the isEmpty() call all together. If your SOQL query returns an empty list for some reason, every time this property is called it will re-query it over and over again always returning the same result of nothing. That isn't efficient and will each up SOQL queries against your limit.

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM

Tags used