Tuesday 17 September 2013

Apex Best Practise


1.       Apex code must provide proper exception handling.
2.       No SOQL or SOSL queries inside loops.
3.        No DML statements inside loops
4.       Avoiding Hardcode IDs.
EX: When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hard coding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against.
Ex:
List<RecordType> rtypes = [Select Name, Id From RecordType where sObjectType='Account' and isActive=true];
Map<String,String> accountRecordTypes = new Map<String,String>{};
     for(RecordType rt: rtypes)
accountRecordTypes.put(rt.Name,rt.Id);
for(Account a: Trigger.new){
if(a.RecordTypeId==accountRecordTypes.get('Healthcare')){  
//code          
}else if(a.RecordTypeId==accountRecordTypes.get('High Tech')){
//code
}
}
5. When querying large data sets, use a SOQL “for” loop.
if the results are too large, the syntax below causes a runtime exception:
Account[] accts=[select Id from Account];--error(because  SOQL query return 50000 returns if we have more than 50000 we use SOQL For loop.itreturns records as batches.each batch has 200 records)
Ex:1
for(Account a :[select Id from Account where Name LIKE ‘Acme%’]){}
Ex:2
for(List<Account>  accts :[select Id from Account where Name LIKE ‘Acme%’]){
update accts;
}
6. No Async (@future) methods inside loops(Exceeds the callouts--10)
7. Use Apex Limits Methods to avoid hitting governor exceptions.
The Limits methods return the specific limit for the particular governor, such as the number of calls of a method or the amount of heap size remaining.
myDMLLimit = Limits.getDMLStatements();
8. Use SOSL over SOQL where possible – it’s much faster.
9.Use Asychronous Apex (@future annotation) for logic that does not need to be executed synchronous.
10.Since Apex is case insensitive you can write it however you’d like. However, to increase readability, follow Java capitalization standards and use two spaces instead of tabs for indentation.
      11.Asychronous Apex should be “bulkified”.
Synchronous:

12.Bulkify your Helper Methods
Prevent SOQL and SOSL injection attacks by using static queries, binding variables or the escapeSingleQuotes method.



No comments:

Post a Comment