Home SALESFORCEAPEX Best Practise to Write Apex
First:

only those variables which are used on visual force page should be public rest all variables should be private, if not used by any other class.


Second:
 the most important thing which we generally ignore while working with visual force wizard is to make variables TRANSIENT which leads to increase the view state size. Use of Transient keyword to declare instance variable that can not be saved, and shouldn’t be transmitted as part of the view state for visual force page.

e.g : Transient Integer tempVar ;
Some apex objects are automatically considered transient, i.e thier value does not get saved as part of page’s view state. These objects are SavePoints , PageReference, XMLStream Classes etc. Static variables also don’t get transmitted thorugh the view state.

Third: 

we should take care of the Heap Size(3 MB) while writing apex. We should nullify all the instance of objects which are no longer in use like if we have a list

//Fetching account records
List accLst = [Select Id, Name From Account Limit 10000] ;

//Creating new map to hold id as key and Account name as value
Map accountMap = new Map() ;

//Putting Id as key and account name as value in map
for(Account tempAcc : accLst) {
     accountMap.put(tempAcc.Id , tempAcc.Name) ;
}

Best way to write query in for loop to avoid filling space of heap by creating a list like :

for(Account tempAcc : [Select Id, Name From Account Limit 10000]) {
    accountMap.put(tempAcc.Id , tempAcc.Name) ;
}

or if we are creating a list to hold account records then we can nullify the list after using it in for loop like :

for(Account tempAcc : accLst) {
   accountMap.put(tempAcc.Id , tempAcc.Name) ;
}

//To reduce heap size
accLst = null ;

Misc steps :
1) Exception handling
2) Commenting
3) Change history tracking (keep history of the changes in class)
4) Query should always contain LIMIT

You may also like

Leave a Comment