- Chris's Picklist
- Posts
- Avoid This Simple Mistake With Apex Collections
Avoid This Simple Mistake With Apex Collections
or the bugs will get you.
Hello Salesforce friends!
I ran into a bug caused by a simple mistake tucked away neatly in some legacy code the other day and thought that it might be a good idea to tell you about it.
Hopefully you can avoid this mistake or at the very least know about it to debug it when it happens to you.
The Mistake
I’m going to show you some code snippets that use a List to show the mistake but keep in mind that this mistake can occur when using any of the collections such as Sets and Maps.
Can you spot the mistake here?
Code Snippet 1
How about here?
Code Snippet 2
One last try.
Code Snippet 3
Did you catch it?
It turns out the issue here is that a dangerous assumption is being made and that’s the fact that we’re treating the “caseList” as if it is initialized.
Now, in the first two code snippets, you might be able to get away with that assumption if you wrote all the code in the org and can guarantee that those methods will NEVER be called from any other method or class that passes in an un-initialized List but that’s one too many variables for my liking and definitely not a good practice.
In the third code snippet, I simply attempted to make the issue easier to understand as the caseList is created in the method but never initialized. That means that the caseList is null and doesn’t have access to the List methods such as “add”.
You will see the following error message when the code is run:
NullPointerException
The Solution
The solution to all of this is to code defensively. Try not to make any assumptions about values passed into your method, even if you’re the one passing them in.
Simply put, this means checking for initialization prior to use for the first two code snippets and NOT forgetting to initialize a list or ANY of the collections such as Sets and Maps, prior to use.
Here’s the first two code snippets written more to my liking:
Code Snippet 1 Fixed
Code Snippet 2 Fixed
Checking for initialization of the collection prior to use is a pretty simple fix that goes a long way to more resilient code, at least in my opinion.
Well, that’s about everything I had to share with you today.
Have any questions related to Salesforce you would like me to make a video or post on? Subscribe to my YouTube channel and leave a comment!
Check out my most recent YouTube Video:
Until next time Salesforce peeps!