Make SDFC happy with use of ‘Lazy Loading’ design patterns


Make SDFC happy with use of ‘Lazy Loading’ design patterns

Lazy loading technique lets the Force.com system fetch only when the respective Visualforce property is null which prevents the Controller’s accessor code from running each time the controller references that property which makes Visualforce pages run more efficiently.

An example

Apex page with account and related opportunities if the stage is won
lazyloading apex

Extension Controller to display related opportunities

//extension controller to display related opportunities
public class ExampleControllerExtension {

  //create an instance account variable to store the passed account record
  Account accountrec;

  public ExampleControllerExtension(ApexPages.standardController std){

    //get the accout record from the standard controller passed through the instance
    accountrec = (Account)std.getRecord();
  }
    // this method fetches the opportunity record every time the property if referenced in the apex page
    public List getRelatedOpprtunities() {
           return [Select Name, Amount, StageName From Opportunity Where AccountId = :accountrec.Id and StageName = ‘Closed Won’];
    }
  
}

//re-write above method using lazy loading - this method fetches the opportunity record only when it is NULL
public List getRelatedOpprtunities {
   get {
        if (relatedOpprtunities == null) {
           relatedOpprtunities = [Select Name, Amount, StageName From Opportunity Where AccountId = :accountrec.Id and StageName = ‘Closed Won’];
        }
      return relatedOpprtunities;
      }
  set;
}

Leave a comment

Your email address will not be published. Required fields are marked *