Apex Code Optimisation Technique

This is a tip for an experienced non-Apex programmer who would like to be a good Force.com Programmatic Developer. You may be an excellent JAVA or .NET programmer. But it does not guarantee that you would be an excellent Force.com developer. But, you can be.

The important point you must always keep in your mind while you are writing your apex code for Force.com application is that your should be optimised. One of the notorious governor limits a Force.com developer (previously an experienced Java/.NET developer) may come across is SOQL limit.

In Java or .NET, we can use SQL anywhere, even inside loops. But, the use of SOQL is restricted in Apex. So, before starting coding, you have to analyse the total data access required for your method logic and you have to create a virtual data model inside your code using the powerful data structures map, set and list. I am pretty sure that an experienced Java or .NET developer knows how these complex structures work.

Let me give a simple example:

Suppose Account, Vehicle and Driver are objects where Account has one ore more Vehicles and a Vehicle has one or more Drivers. You need to write a trigger on Account to set some values of Driver records based on some conditions. As a Java or .NET developer, you expect the code to be like:

for (Account acc : [select Id, (select ..... from Vehicles__r) from Account where Id in trigger.newMap.keySet()) {

for (Vehicle__c veh : [select Id, (select ... from Drivers__r) where AccountId__c = :acc.Id]) {

for (Driver__c driv : [select .... from Driver__c where VehicleId__c = :veh.Id) {

if (blahblah) driv.ddgdg = 'asdasdsd';

} } }

You may think like you have done a wonderful job. :-) But the reality is that you will be flooded with SOQL governor limits. So, what you should do is that you should analyse the relationships and you have to create a virtual data model and you can use that model inside loops.

map<ID, Account> - account map, map<ID, map<ID, Vehicle__c>> mapOfAccountIdToVehicleMap map<ID, map<ID, map<ID,Driver__c>>> mapOfAccountIdToMapOfVehicleIdToDriverMap

These are some examples of virtual data model you can create inside your code. I think this may help you.

To view or add a comment, sign in

More articles by Shabu Thomas

Others also viewed

Explore content categories