Skip to main content

Top four design patterns and algorithm that every Salesforce Developer should know

A few days ago I was speaking to a developer friend, he was asked about a Singleton design pattern and he had no idea about. He spoke about how we developers never talk about patterns. And that time it hit me, we developers do not talk about design patterns and algorithms. There are many design patterns available off the shelf, they talk in detail about the problems they can solve. However, in my experience, I have come across and used the following


1. Singleton

This is one of the most common and important design pattern to be used. When initiating objects, we need to make sure only one instance of the object is initiated. In a multi-tenant system like Salesforce, it becomes imperative that we do not hog more resources than needed
Lets look at an example

trigger AccountTrigger on Account (before insert, before update) {
    for(Account record : Trigger.new){
        AccountMasterRecordType rt = new AccountMasterRecordType ();
        ....
    }
}

public class AccountMasterRecordType {
string recordTypeid;
public string AccountMasterRecordType (){
    string recordTypeid = Account.sObjectType.getDescribe().getRecordTypeInfosByName().get('Client').getRecordTypeId();
   }
}




When we apply Singleton pattern, the AccountMasterRecordType Handler changes to this,

public class AccountMasterRecordType {
    // private static variable referencing the class
    private static AccountMasterRecordType instance = null;
    public String recordTypeid{get;private set;} // the id of the record type

    // The constructor is private and initializes the id of the record type
    private AccountMasterRecordType (){
        recordTypeid= Account.sObjectType.getDescribe()
            .getRecordTypeInfosByName().get('Client').getRecordTypeId();
    }
>


// a static method that returns the instance of the record type
    public static AccountMasterRecordType getInstance(){
        // lazy load the record type - only initialize if it doesn't already exist
        if(instance == null) instance = new AccountMasterRecordType();
        return instance;
    }
}

In the Singleton framework pattern, we initialise every object only once. Not only do we save precious resources but we can also save DMLs and running into governor limits using the framework. More information about singleton

2. Decorative

I have used decorator pattern for ages. One of the most common implementation is when you have to build a visualforce page with checkbox selectors. You have capture or display attributes that are not present on the object, you can use the decorative framework.

For e.g.,

public with sharing class WrapperDisplay{
 public List<OpportunityDecorator> lstwrapperOpp {get;set;}
 
 public WrapperDisplay(){
  lstwrapperOpp = new List<OpportunityDecorator>();
  for(opportunity opp : [select Id, Name from opportunity limit 10]){
   lstwrapperOpp.add(new wrapper(opp));
  }
 }
 //Wrapper Class Construction

    public class OpportunityDecorator{
       Boolean Select;
       Opportunity opp;
       // Wrapper class constructor
       public OpportunityDecorator(opportunity opp){
       opp=opp;
      }  
    }
}


3. iTrigger factory pattern

This topic is very vast and there are multiple blog posts written on this topic. There is no common trigger pattern but one that is heavily recommended is the iTrigger factory pattern by Tony Scott.
Trigger pattern is essential to normalise your trigger and control the flow of execution. Given any salesforce project, there will be instances of writing a trigger.

The majority of governor issues will arise in and around writing bad triggers and most of them can be quelled by using a good trigger pattern. You can read the original trigger pattern here



/**
 * Interface containing methods Trigger Handlers must implement to enforce best practice
 * and bulkification of triggers.
 */
public interface ITrigger
{
    /**
     * bulkBefore
     *
     * This method is called prior to execution of a BEFORE trigger. Use this to cache
     * any data required into maps prior execution of the trigger.
     */
    void bulkBefore();
 
    /**
     * bulkAfter
     *
     * This method is called prior to execution of an AFTER trigger. Use this to cache
     * any data required into maps prior execution of the trigger.
     */
    void bulkAfter();
 
    /**
     * beforeInsert
     *
     * This method is called iteratively for each record to be inserted during a BEFORE
     * trigger. Never execute any SOQL/SOSL etc in this and other iterative methods.
     */
    void beforeInsert(SObject so);
 
    /**
     * beforeUpdate
     *
     * This method is called iteratively for each record to be updated during a BEFORE
     * trigger.
     */
    void beforeUpdate(SObject oldSo, SObject so);
 
    /**
     * beforeDelete
     *
     * This method is called iteratively for each record to be deleted during a BEFORE
     * trigger.
     */
    void beforeDelete(SObject so);
 
    /**
     * afterInsert
     *
     * This method is called iteratively for each record inserted during an AFTER
     * trigger. Always put field validation in the 'After' methods in case another trigger
     * has modified any values. The record is 'read only' by this point.
     */
    void afterInsert(SObject so);
 
    /**
     * afterUpdate
     *
     * This method is called iteratively for each record updated during an AFTER
     * trigger.
     */
    void afterUpdate(SObject oldSo, SObject so);
 
    /**
     * afterDelete
     *
     * This method is called iteratively for each record deleted during an AFTER
     * trigger.
     */
    void afterDelete(SObject so);
 
    /**
     * andFinally
     *
     * This method is called once all records have been processed by the trigger. Use this
     * method to accomplish any final operations such as creation or updates of other records.
     */
    void andFinally();
}


This code is just as an example. Read the original blog post for complete implementation.

4. Strategy

The iTrigger interface mentioned above brings us, by design, for the Strategy implementation design pattern. The strategy pattern allows us to define a family of algorithms, that can be selected and changed at runtime.

An example for this is,

public interface paymentStrategy{
    Boolean pay(double amount);
}

public class creditCardStrategy implements paymentStrategy{
        private String name;
 private String cardNumber;
 private String cvv;
 private date dateOfExpiry;

public boolean pay(double amount){
//Credit card interface using apexRest
   }
}

  public class paypalstrategy implements paymentStrategy{
        private string emailid;

   public boolean pay(double amount){//paypal interface using apexRest
  }
}


Those are the top four patterns you should know about. What are some of the patterns you have used and how? Let me know in the comments below.

References:
Apex Design Pattern
iTrigger 

Comments

Popular Post

The unofficial guide to become a Certified Salesforce Administrator (ADM 201)

In my attempt at maximum certifications in 60 days, I completed Salesforce Certified Administrator exam on February 11th 2013 So you have decided to ramp up your career and take certifications in your hand. Good choice. It is also likely that this is the first time you have heard of Salesforce, certification and since your company has a vision of you completing the certification you have decided to do it. At this stage it is likely that, You have done extensive googling. You have received countless brain-dumps. And you have received plenty of advise from different types of users which ranges from Admin certification is easier than making coffee to Admin certification is tougher than building a rocket-ship to fly off to the moon. The purpose of this guide is to give you a clear understanding of what to expect when you are expected to become Certified Salesforce Administrator. To bring sense to all the things you have seen so far and to clearly explain what to do and what

Some PDF tricks on Visualforce: Landscape, A4, page number and more

The beauty of Visualforce is simplicity. Remember the shock you received when you were told the entire page renders as PDF if you just add renderAs=PDF to the Page tag. For those who thought I spoke alien language right now, here is the trick, to render a page as PDF, we add a simple attribute to the <apex: page> tag <apex: page renderAs='pdf'> This will render the entire page as PDF. Now, say we need to add some extra features to the PDF. Like a page number in the footer or we need to render the page in landscape mode. Faced with this problem, I put on my Indiana Jones hat and went hunting for it in the vast hay-sack of the internet (read: googled extensively). Imagine my happiness when i found a big big page with many big big examples to solve the problem. The document I am referring to is from W3C, paged Box media . Long story short, I now possess the ultimate secret of rendering the page in any format I want. So here are few tricks I learned from the p

The Basics of writing a Apex Trigger

One of the most important and common asked question on Forums and everywhere is how do I write a trigger. Coding in Apex Trigger is like going to a dentist for a root canal, you keep dreading the moment until you realize it is actually not going to hurt you. If you plan to write an Apex Trigger this quick guide will help you doing so. The first and foremost rule in writing a trigger is to remember the oldest suggestion given to the most comprehensive Hitchhikers Guide to Galaxy, ' Don't Panic. ' Writing a trigger is not a rocket science, in-fact we should thank the team at Salesforce and ForceDotCom for making everything so simple, that anyone can do it. Enough of talk, lets code. So you want to write a trigger. Let us have a glimpse of what we are going to build. The problem statement is as follows Problem:  When the User is entering the Opportunity, check for the Opportunity Amount. If the Opportunity Amount is greater than 50,000. Mark the Parent Account as