Thursday, December 19, 2019

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 
Share:

0 comments:

Post a Comment