Friday, April 28, 2017

Salesforce Apex Best Practices

Best Practices in Apex Coding

    1.       Avoid DML statement like insert, update and delete inside the looping statement
Example :
List<Account> lstAcc = new List<Account>();
for (i=0; i<=100; i++) {
Account acc = new Account();
Insert acc;
}

    2.       Coding standards should be followed as Apex Developer Guide,
Coding standard helps other people to understand the process. Apex coding standard is similar to java, So developer comes from Java background easy to understand and follow coding standards in Apex
2.1    Class name should start with Capital letter ex : public class Invoice{}
2.2    Variable name should start with small letters ex: String count;
2.3    Method name should start with small letters ex : public void calc() {}
2.4    Provide space in looping statement ex : if () { }, for () { }
2.5    Only method has bracket immediately after the name ex : public void calculator()

    3.       Make sure used Salesforce.com standard functionality wherever possible, instead of customizing the code.

    4.       While production deployment should remove unwanted debug statements, because, more debug statement may slow down the process. For example, if you debug the collections inside the looping statement,  it will print multiple times with huge collection of data
Ex :
Map<Id, List<Account>> mapAcc = new Map<Id, List<Account>>();
for (int i=0; i<=100; i++) {
   System.debug(‘Test’+mapAcc); // should avoid this in production system
}

    5.       Leverage the collections in coding for efficient and optimal coding, Salesforce.com offer following collection statement List, Set, and Maps.

   6.       In complex business logics, should use proper trigger context, it saves lot of saving times, for example before trigger event no need of additional DML statements. After update use old (Trigger.OLD) values instead of additional query wherever possible.

   7.       It is better practice to use comments /* */, it provide explanation of the method, however, comment should be updated properly if any changes in the corresponding methods or classes. Otherwise it leads to lot of confusions for future changes.

   8.       As a apex developer should familiarize with order of execution, I have seen people overlooked on Validation rule executed before the all after triggers. So need to understand the flow correctly in the way to detect the problems.

   9.       In all DML statement should be inside try and catch statement, as well exception should be handled efficient way.
Try {
insert acclist;
} catch (Exception e) {
   // handle the exception
}

   10.    Variable name of collections should reflect accordingly, for example if it is Map<ID,String> then variable name should reflect as mapInventory or inventoryMap;