Friday, June 5, 2015

Implementing Singleton Design Pattern in Apex - Use Case III


This post is part of the series - Design Pattern in Apex

Today in this post I will explain how Singleton Design Pattern can 
be used to call global describe only once.

Requirement -

When someone inserts an account record, you need to inspect all the fields in the account object.

Implementation -
Below is the trigger to start with -
MyAccountTrigger-

AccountHelper -

The problem with this approach is that when someone enters huge number of accounts with dataloader, this code will work like -
For each insert, it will create a new instance of AccountHelper which in turn will execute GlobalDescribe(). Very soon we will be hit by LimitException.

To avoid that, we have to implement Singleton Design Pattern and below are the changes we need to do that -
AccountHelper -

MyAccountTrigger-

Now you can see for a single transaction, we are calling GlobalDescribe only once because we are now not instantiating AccountHelper object for each Account insert, rather we are only instantiating one AccountHelper object per transaction.

Hope you understood the usages of Singleton Design Pattern. If you have implemented this design pattern in any other situation, requesting you to share here. Thanks for your feedback. Thanks.

0 comments:

Post a Comment