1

In the doc from salesforce, there is the following example.

public class MyClass {
 
    class RGB {
 
        Integer red;
        Integer green;
        Integer blue;
 
        RGB(Integer red, Integer green, Integer blue) {
            this.red = red;
            this.green = green;
            this.blue = blue;
        }
     }
 
    static Map<String, RGB> colorMap = new Map<String, RGB>();
 
    static {
        colorMap.put('red', new RGB(255, 0, 0));
        colorMap.put('cyan', new RGB(0, 255, 255));
        colorMap.put('magenta', new RGB(255, 0, 255));
    }
}

Is that the recommended approach? What is the difference between that and the following one?

public class MyClass {
 
    class RGB {
 
        Integer red;
        Integer green;
        Integer blue;
 
        RGB(Integer red, Integer green, Integer blue) {
            this.red = red;
            this.green = green;
            this.blue = blue;
        }
     }
 
    static Map<String, RGB> colorMap = new Map<String, RGB>{
        'red' => new RGB(255, 0, 0),
        'cyan' => new RGB(0, 255, 255),
        'magenta' => new RGB(255, 0, 255)
    };

}

I was under the impression that initialising the Map on the declaration is more efficient than creating an empty Map and putting elements one by one. Is that wrong?

I would understand that if it would be done on a getter, it would be a "lazy" initialisation, but is not the case, is it?

What am I missing here?

1
  • FYI. Examples from official Salesforce docs can be really bad. From inefficient through anti-patterns up to straight up errors in code. Their example for implementing Comparable interface gave nonsense results if there was at least 1 null value. So I wrote them. Now they "fixed" it and it's only convoluted, hard to read and have 2 times more checks than necessary, but gives correct results :)
    – Kacper A
    Nov 5, 2020 at 15:05

1 Answer 1

1

Yes, initializing a map directly is more efficient than using Map.put. The static block example was more illustrative than prescriptive. The point is, if you need to execute logic when the class is loaded, you can use a static block initializer. This is the equivalent of using a constructor to initialize instances of your class. I prefer static blocks over inline initialization in order to group everything together (I find it more legible this way).

For example, if you needed to query a list of metadata and then put them into a structure, you'd want a static block initializer. Of course, some prefer to use inline initialization, and as long as it's possible, that's fine. I would recommend not mixing the two; either initialize inline or in a static block, but not both. This lends to readability of the class.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .