Nov 22, 2010

Best Practise to Write Apex

Hi All,

It is about what all areas are to be covered while writing Apex code.

Firstly 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.

Secondly 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.

Thirdly, 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


Thanks

13 comments:

  1. Hey I am facing a view state error. I checked in the view state option and it shows that the query which i use returns around 2500 records which jump the limit of 135 Kb. are there any workarounds other that putting a limit on the query.

    Thanks in advance

    ReplyDelete
  2. I would "clear" the list than nullifying it.
    Means, doing "accLst.clear()" instead of "accLst=null". I think nullifying the list may not freeup the heap memory. But again, need to be cautious of Nullpointer excepion.

    ReplyDelete
  3. Thanks.

    The advise for setting the list to null was very helpful.

    ReplyDelete
  4. always followed your these 3 steps so far and most of the time 3rd point itself helped me deal with view state issue also.

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete