I am working on an app which we plan to publish on app exchange. As per pre-requisite requirement by salesforce, any app before getting listed on app exchange should go through code review from checkmarx. To comply with this, we submitted our code base to checkmarx. We were surprised to see one of problem reported by checkmarx. The error says "Bulkify Apex Methods - Using Collections in methods". Code snippet in question is (I have to hide my business logic :) ):-
List<Account> lstAccount = new List<Account>();
Integer i = 0;
for(Account acct : [Select Id, Name from Account]){
lstAccount.add(acct.Name = 'Test Account' + i);
i++;
}
if(lstAccount.size() > 0)
update lstAccount;
I was wondering what is wrong with this, as it seems perfect. I went to http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_loops_for_SOQL.htm to understand 'SOQL for Loop Formats'. As per this url, the summary says:-
SOQL for loops can process records one at a time using a single sObject variable, or in batches of 200 sObjects at a time using an sObject list:
- The single sObject format executes the for loop's <code_block> once per sObject record. Consequently, it is easy to understand and use, but is grossly inefficient if you want to use data manipulation language (DML) statements within the for loop body. Each DML statement ends up processing only one sObject at a time.
- The sObject list format executes the for loop's <code_block> once per list of 200 sObjects. Consequently, it is a little more difficult to understand and use, but is the optimal choice if you need to use DML statements within the for loop body. Each DML statement can bulk process a list of sObjects at a time.
So, even salesforce says 'The sObject list' format is more efficient. As per this, I make change in my code base as below:-
for(List<Account> lstAccount : [Select Id, Name from Account]){
for(Integer i=0; i<lstAccount.size(); i++){
lstAccount[i].Name = 'Test Account' + i;
}
update lstAccount;
}
if(lstAccount.size() > 0)
update lstAccount;
And guess what, when I submitted my modified code to Checkmarx, this error is gone.
Comments
Post a Comment