Apex Design Pattern
As a developer in salesforce when we get any requirement, we usually started writing classes and trigger without following design pattern. Recently I came across the salesforce apex design pattern which is also available here. Let's go through the available apex design pattern.
Singleton Design Pattern
The singleton pattern attempts to solve the issue of repeatedly using an object instance, but only wishing to instantiate it once within a single transaction context.
Problem:
The following code will initialize the same object multiple time.
If we go with the below approach, as describe call is depend on the type of object and it will increase the CPU time used and ultimately it may lead to breach of governor limit(Apex CPU time limit exceeded) in salesforce.
Solution:
Instead of initializing the object multiple times we can use singleton pattern which will initialize the object only once like below example
Singleton Design Pattern
The singleton pattern attempts to solve the issue of repeatedly using an object instance, but only wishing to instantiate it once within a single transaction context.
Problem:
The following code will initialize the same object multiple time.
If we go with the below approach, as describe call is depend on the type of object and it will increase the CPU time used and ultimately it may lead to breach of governor limit(Apex CPU time limit exceeded) in salesforce.
for(Integer i = 0; i < 100000; i++) {
DescribeSObjectResult recordTypeId = SObjectTypeDescribe.getDescribeAccount();}
public class SObjectTypeDescribe {
static DescribeSObjectResult instance;
public static DescribeSObjectResult getDescribeAccount() {
instance = Account.SObjectType.getDescribe(); //Initialising the object multiple times for every call.
return instance;
}
}
Solution:
Instead of initializing the object multiple times we can use singleton pattern which will initialize the object only once like below example
public class SObjectTypeDescribe {
static DescribeSObjectResult instance;
public static DescribeSObjectResult getDescribeAccount() {
if(instance == null){
instance = Account.SObjectType.getDescribe(); // Intialize object only once otherwise it will use the previous instance
}
return instance;
}
}
Comments
Post a Comment