Reader small image

You're reading from  Apex Design Patterns

Product typeBook
Published inApr 2016
Reading LevelBeginner
Publisher
ISBN-139781782173656
Edition1st Edition
Languages
Right arrow
Authors (2):
Anshul Verma
Anshul Verma
author image
Anshul Verma

Anshul Verma has been working on the Salesforce platform since 2006. Prior to that, he has done extensive development using MS technologies on web, desktop, and mobile applications. He possesses a tremendous understanding of enterprise-scale systems and has worked in designing intricate systems with high scalability, performance, and robustness. He has been a Dreamforce speaker and is a regular contributor to Stack Exchange and other developer communities. He has four Salesforce certifications and is currently working as a project manager and technical architect where he is responsible for managing customer success and delivering high-quality solutions to his clients. He has conducted various training sessions in his current organization and trained over 50 new hires. He is very popular with his training batches and can be often found sharing his knowledge with his team and peers. He owns and maintains his blog (http://mightycoder.blogspot.com/), and you can follow him on Twitter at @toanshulverma.
Read more about Anshul Verma

Jitendra Zaa
Jitendra Zaa
author image
Jitendra Zaa

Jitendra Zaa has been working on the Salesforce platform since 2008. He has extensively worked on Java and .NET-based enterprise applications. He also has experience in working with multiple JavaScript libraries, web frameworks, ETL tools, and databases. He is an expert in designing and implementing integrations of Salesforce with external systems. He is a regular speaker at the worlds biggest developer event, Dreamforce, mostly in developer track. Because of his contributions to the Salesforce community, he has also been awarded the Salesforce MVP title. He has more than eight Salesforce certifications and works as a Salesforce technical architect. He owns one of the most viewed Salesforce developer blogs (http://www.JitendraZaa.com), formerly, http://Shivasoft.in. You can follow him on Twitter at @JitendraZaa.
Read more about Jitendra Zaa

View More author details
Right arrow

Chapter 2. Creational Patterns

Apex programming revolves around objects and classes. During the course of application development, we create multiple classes. Also, we create objects of these classes to satisfy business requirements. Creating an object of a class within another class, creates dependency between those classes. This is also known as tight coupling.

As discussed in the previous chapter, tight coupling is considered inferior, as it can negatively impact the code's maintainability and scalability. Creational design patterns can help us avoid tight coupling by hiding the object creational logic.

Creational design patterns can be considered in the following scenarios:

  • Instantiating classes in the Apex Scheduler class. If we directly instantiate the Apex class in scheduler using new keyword, then the class gets serialized and, therefore, locked for further changes.
  • Using multiple classes while creating test data in test classes.
  • Creating code libraries only to reveal their usage and...

Factory method pattern


Often, we find that some classes have common features (behavior) and can be considered classes of the same family. For example, multiple payment classes represent a family of payment services. Credit card, debit card, and net banking are some of the examples of payment classes that have common methods, such as makePaymentauthorizePayment, and so on. Using the factory method pattern, we can develop controller classes, which can use these payment services, without knowing the actual payment type at design time.

Note

The factory method pattern is a creational design pattern used to create objects of classes from the same family without knowing the exact class name at design time.

Using the factory method pattern, classes can be instantiated from the common factory method. The advantage of using this pattern is that it delegates the creation of an object to another class and provides a good level of abstraction.

Let's learn this pattern using the following example:

The Universal...

Abstract factory pattern


The Universal Call Center company is growing very fast, and they have a small Force.com application where agents can log a request to place an order for a new computer. Developers have just learned about the factory method design pattern and are very excited to implement the same design pattern in this scenario as well. They decided to create an interface of the computer type and its different implementations, such as high-configuration and low-configuration computers. However, they were disappointed when they heard that they need to support various types of configurations other than low and high configurations. For example, some computers need high end processors but small monitors and less storage. There were a few requests regarding an average processor but an LCD monitor and SSD storage.

By this time, developers realized that the factory method pattern cannot be used in this scenario. Let's see how they solved this problem.

The abstract factory pattern is used...

The singleton pattern


The singleton design pattern restricts the instantiation of a class to only one object.

This is a useful design pattern in Apex and is frequently used. As discussed in the previous chapter, Salesforce has various governor limits; for example, a number of SOQL queries, a number of query rows returned, and a number of DML operations that can be performed in a single request.

Using the singleton design pattern, we can make sure that utility classes are instantiated only once, which can help in avoiding governor limits.

The sales division of a call center receives calls either from a customer or broker who is interested in the product. If a call comes directly from a customer, then the call center agents need to create a new opportunity record with all the required information. Alternatively, if a call comes from a broker, then the call center agents need to create an opportunity record and then record it for a broker as well. Brokers are eligible for commission if they sell...

The builder pattern


The builder pattern is used to instantiate an object of a complex class using the step-by-step approach and return a constructed object at once.

The intention of the factory method and abstract factory method patterns is to use polymorphism to construct objects, as discussed in the initial part of this book. However, in this design pattern, a new independent Builder class is used to construct objects. This pattern is very useful when many parameters are needed to construct and initialize an object.

Developers of Universal Call Center were enjoying their success after the implementation of the singleton pattern and resolving excess SOQL queries. Now, it was time to write a test class for the code written in the singleton design pattern.

Developers came up with the following test class:

@isTest(SeeAllData = false) 
public class OpportunityTriggerTest { 
     
    //Test method to test if state is populated 
    //on Opportunity and Brokers 
    static...

The prototype pattern


The prototype design pattern is used to create a new object of a class based on an existing object of the same class. It helps avoid the repetitive code used to initialize a newly created object.

Developers of Universal Call Center solved many problems associated with the creation of an object, using design patterns, such as the factory method, singleton, abstract factory method, and builder pattern. Now, they are confident about how to simplify, manage, and solve problems created while instantiating objects. They were working on the module of an application where they needed to create a duplicate copy of the Apex helper class used to perform various operations.

The following is a code snippet of a wrapper class, which simply sets and gets the Opportunity object:

public class OpportunityWrapper { 
     
    private Opportunity opp ; 
     
    public void setOpportunity(Opportunity o){ 
        opp = o ; 
    } 
     
    public...

Summary


In this chapter, we discussed how to deal with various situations while instantiating objects using design patterns, such as the factory method, abstract factory method, singleton, builder, and prototype pattern.

The following table shows a summary of the design patterns discussed in this chapter:

Design patterns 

Summary

The factory method pattern

This creates objects of the same family of classes.

The abstract factory pattern

This creates a single object consisting of objects of different factories to represent a related product.

The singleton pattern

This restricts to a single instance of a class.

The builder pattern

This hides the complexity and sequence to initialize a complex object.

The prototype pattern

This creates a new object on the basis of an existing object of the same type.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Apex Design Patterns
Published in: Apr 2016Publisher: ISBN-13: 9781782173656
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Anshul Verma

Anshul Verma has been working on the Salesforce platform since 2006. Prior to that, he has done extensive development using MS technologies on web, desktop, and mobile applications. He possesses a tremendous understanding of enterprise-scale systems and has worked in designing intricate systems with high scalability, performance, and robustness. He has been a Dreamforce speaker and is a regular contributor to Stack Exchange and other developer communities. He has four Salesforce certifications and is currently working as a project manager and technical architect where he is responsible for managing customer success and delivering high-quality solutions to his clients. He has conducted various training sessions in his current organization and trained over 50 new hires. He is very popular with his training batches and can be often found sharing his knowledge with his team and peers. He owns and maintains his blog (http://mightycoder.blogspot.com/), and you can follow him on Twitter at @toanshulverma.
Read more about Anshul Verma

author image
Jitendra Zaa

Jitendra Zaa has been working on the Salesforce platform since 2008. He has extensively worked on Java and .NET-based enterprise applications. He also has experience in working with multiple JavaScript libraries, web frameworks, ETL tools, and databases. He is an expert in designing and implementing integrations of Salesforce with external systems. He is a regular speaker at the worlds biggest developer event, Dreamforce, mostly in developer track. Because of his contributions to the Salesforce community, he has also been awarded the Salesforce MVP title. He has more than eight Salesforce certifications and works as a Salesforce technical architect. He owns one of the most viewed Salesforce developer blogs (http://www.JitendraZaa.com), formerly, http://Shivasoft.in. You can follow him on Twitter at @JitendraZaa.
Read more about Jitendra Zaa