S

Stop Checking if Lists are Empty

Updating a list in Salesforce

If I have one major pet peeve with Salesforce programmers, it’s this one: stop checking if your lists are empty before every DML statement. I’m not sure how this became to be seen a best practice, and it’s possible that at one point it was necessary but this has long since not been the case.

In Apex, this manifests itself in an if statement that looks like this:

if(!listName.isEmpty()) {
update listName;
}

Essentially, if the list isn’t empty update the records in the list.

It’s totally unnecessary to do this: the update call itself checks this, and there’s no impact on governor limits or SOQL statement use. This is ridiculously easy to confirm, and yet I still see examples like the one above.

To confirm, you can run two lines of code in an anonymous apex window.

List listName = new List();
update listName;

After this has executed, review the log and check the statistics at the bottom. You should see something like this:

So to all my fellow Salesforce, please stop doing this. Practically speaking the impact may be marginal, but you’re actually slowing things down by having Salesforce fun a check twice when it could just be run once. Your code is harder to read, it’s longer and may not be covered by a test class if you don’t handle them properly. It’s just a waste.

Leave a Reply

Your email address will not be published. Required fields are marked *