Apex allows us to develop any custom solution. This post is an aggregate of common design patterns and associated best practices for Apex development. Knowing these patterns will not only help you achieve excellence in daily development but also will prepare you to rock any Developer interview.
Apex allows us to develop any custom solution. This post is an aggregate of common design patterns and associated best practices for Apex development. Knowing these patterns will not only help you achieve excellence in daily development but also will prepare you to rock any Developer interview.
Singleton — minimizing object instantiation for improved performance and to mitigate the impact of governor limits
Strategy — defining a family of algorithms, encapsulating each one and making them interchangeable and selectable at runtime
Decorator — extending the functionality of a sObject in Apex
Bulk State Transition — efficiently tracking the change of a field value in a trigger and executing functionality based on this change
Composite — treating a group of objects in a similar manner to a single instance of that object
The intent of the Singleton pattern is to provide only a single instance of the class and that instance can be used anywhere throughout the transaction.
In other words,
The application needs one, and only one, an instance of an object. Additionally, lazy initialization and global access are necessary.
The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance.
The office of the President of the India is a Singleton. The Indian Constitution specifies the means by which a president is elected, limits the term of office, and defines the order of succession. As a result, there can be at most one active president at any given time. Regardless of the personal identity of the active president, the title, “The President of the India” is a global point of access that identifies the person in the office.
Credit – https://sourcemaking.com/design_patterns/singleton
Let’s say you are integrating the Stripe Payment gateway with Salesforce and need to send the data to Stripe on certain actions. For Example, Account Creation.
You have developed the following apex call as initial version
If you notice that, in the above code we are making the SOQL query for both the methods and there could be more methods. Now consider, that if there is bulk data then you will get into SOQL Governor Limit.
Let’s modify the code and have a separate method do make the SOQL Query
We have made the changes and kept the query in a separate method. However still if there are many records you will get into Governor Limit.
Let’s develop the same using the Singleton pattern.
In the above code, we have implemented the Singleton Pattern and now the instance will only be initialized once.