We assume that you are reading this book because you have encountered situations where you have had the same design requirement multiple times, or seen a repetitive problem that has always been solved with the same solution. Those design solutions that are applied again and again to the same type of problem are also known as design patterns.
To better understand the application of design patterns in everyday life, let's take a look at the example of the ATM machine. Every ATM machine needs to have a slot where an ATM card can be inserted, there is a keypad to enter a secret pin, and there is a panel from where the cash can be dispensed. This core functionality of an ATM machine can be considered as a design pattern. Some banks need extra functionalities, such as bill pay or mobile recharge, and they can simply extend this design pattern as per their requirements.
No one would like to reinvent the wheel if an industry-proven solution already exists for a problem, and using such a proven solution would save them time and effort. Furthermore, it also ensures a scalable, robust, and future-ready solution.
In this book, we will discuss the challenges in application development using Apex, common repetitive problems, and most accepted solutions. We have structured our content considering the Apex development platform and blended it with day-to-day challenges that we face during development.
We will first explain the common concepts of application development, which are the building blocks for design patterns. Understanding these concepts is very important as all the design patterns are combinations of one or more principles explained in a later section.
It is not necessary that design patterns should fulfill all requirements so why can't we innovate our own better solution?
Yes, innovation is necessary; and certainly, we can come up with a better design and solution or even a new design pattern. Let's take the preceding example; instead of entering a secret pin, a user can use voice recognition for authentication purposes'. It may look cool to some people, but for many it may be a security concern. Speech recognition may not work because of different accents and so on. My point here is that innovation comes at a cost. In software industry, we don't always have the privilege of time because of project timelines and other dependencies.
Design patterns are age-tested and recommended techniques to address a given problem. They not only help in solving the problem at hand, but also address various possible offshoots of the central problem. Design patterns have also evolved as per requirements and will continue to do so.
We are not suggesting that you have to use only design patterns. Every problem is unique and a design pattern can solve only some part of the problem. However, you need to think, design, and come up with your own version of an extended design. Design patterns are very generic and basic; they mostly guide you through the flow of the creation of an object or manipulate the behavior at runtime or structure your code. A design pattern is not a finished code solution, but it is a recommended code structure. Choosing the right design pattern for a given problem is very important and needs thorough understanding. With increasing use of design patterns, you can further enhance your development skills and understand how to best structure your code.
Any language that supports the following four pillars of Object-Oriented Programming is known as an Object-Oriented Programming (OOP) language:
- Inheritance: This is the ability to extend an existing class to add a new functionality
- Polymorphism: This is the ability to perform different actions by calling the same method
- Abstraction: This is the ability to hide complex implementation
- Encapsulation: This is the ability to bind data attributes and behavior together
Let's take an example of the childhood game Mario to understand OOPs. The following class shows some basic information about Mario and its capabilities:
public class Mario { public void ability(){ System.debug('I can Walk'); } public void info(){ System.debug('I am Mario'); } }
This ability to bind the capabilities of Mario in the same place is called encapsulation.
Like any other games, there are power boosters, such as speed running, bullets, and so on. If we want to change the behavior of Mario in the game, some more code can be added to the existing class with conditions. However, the chances are high that an existing application will break due to the introduction of the new code. OOP suggests that you do not modify the existing code but extend it so that testing can be done only on the new code and there are fewer maintenance issues. To resolve this, we can use Inheritance.
Note
To use inheritance in Apex, we need to use the virtual
or abstract
keywords in the base class and methods.
To use inheritance, we need to use the virtual
keyword in the base class and methods. The virtual
keyword states that a class or method can be inherited and overridden by child classes. We need to make some modification in the preceding Mario
class, informing Apex about what can be overridden. We only need to override the ability
method in the child class, so we need to mark it as the virtual
method. In order to inherit this class, it should also be declared with the virtual
keyword:
public virtual class Mario { public virtual void ability(){ System.debug('I can Walk'); } public void info(){ System.debug('I am Mario'); } }
Let's see how a child class can be written in Apex:
public class Mario_Run extends Mario {
public override void ability(){
super.ability();
System.debug('I can Run);
}
}
The following figure shows a parent-child relationship between classes:

The extends
keyword is used in a child class to inform a parent class. If we are writing the same method again in a child class of a parent class, then the override
keyword needs to be used. The override
keyword informs Apex that this is a new version of the same method in the parent class. If we want to call any method in a parent class, we need to use the super
keyword.
Run the following code as an anonymous Apex script from the developer console to understand inheritance:
Mario obj = new Mario(); obj.info(); obj.ability(); System.debug('----- Mario with power booster ----- '); obj = new Mario_Run(); obj.info(); obj.ability();
The output will look something like this:
I am Mario I can Walk ----- Mario with power booster ----- I am Mario I can Walk I can Run
As we can see, in the preceding code snippet, a child class is able to reuse a parent class method with an added behavior. The type of object is Mario
, which is the parent class, but Apex is able to call a method of the Mario_Runclass
using dynamic dispatch, which is a kind of Polymorphism.
Note
Assigning a child class reference to a parent class is known as subtype polymorphism. Read more about subtype polymorphism at https://en.wikipedia.org/wiki/Subtyping.
Types of polymorphism can be identified on the basis of when an implementation is selected. In this approach, when an implementation is selected at compile time, it is known as static dispatch. When an implementation is selected while a program is running (in case of a virtual method), it is known as dynamic dispatch.
An interface is another way to achieve polymorphism and abstraction in Apex. Interfaces are like a contract. We can only add a declaration to a class but not the actual implementation. You might be thinking about why do we need to create a class, which does not have anything in it? Well, I will ask you to think about this again after taking a look at the following example.
We will continue with the Mario example. Like any game, this game also needs to have levels. Every level will be different from the previous; and therefore, the code cannot be reused. Inheritance was very powerful because of the dynamic dispatch polymorphic behavior; however, inheritance can not be used in this scenario.
We will be using an interface to define levels in a game. Every level will have its number and environment:
public interface GameLevel {
void levelNumber();
void environment();
}
The preceding interface defines two methods that need to be implemented by child classes. The interface
keyword is used to define an interface in Apex:
public class Level_Underground implements GameLevel { public void levelNumber(){ System.debug('Level 1'); } public void environment(){ System.debug('This level will be played Underground'); } } public class Level_UnderWater implements GameLevel { public void levelNumber(){ System.debug('Level 2'); } public void environment(){ System.debug('This level will be played Under Water'); } }
The preceding two classes implement GameLevel
and make sure that both the methods have been implemented. A compiler will throw an error if there is any mistake in implementing a child class with a different method signature.
The following class diagram shows two classes implementing a common interface:

The anonymous Apex code for testing is as follows:
GameLevel obj = new Level_Underground(); obj.levelNumber(); obj.environment(); obj = new Level_UnderWater(); obj.levelNumber(); obj.environment();
The output of this code snippet is as follows:
Level 1
This level will be played Underground
Level 2
This level will be played Under Water
We cannot instantiate interfaces; however, we can assign any child class to them; this behavior of an interface makes it a diamond in the sea of OOP.
In the preceding code, obj
is defined as GameLevel
; however, we assigned Level_Underground
and Level_UnderWater
to it, and Apex was able to dynamically dispatch correct the implementation methods.
Huge applications and APIs are created using interfaces. In Apex, Queueable
and Schedulable
are examples of interfaces. Apex only needs to invoke the execute()
method in your class because it knows that you follow the contract of an interface.
An abstract class is something between inheritance and an interface. In inheritance, a child class extends a parent class, where both the classes have full implementations. In an interface, a parent class does not have any implementation and depends on child classes completely. There are scenarios where a parent class knows the common implementations needed by all child classes but the remaining implementation differs for all.
In the same game that we discussed earlier, there are multiple ways to gain points. If Mario gets any coin, then the overall score will be added (known), but there are different kinds of coins (unknown). Coins may be in blue, yellow, or different colors. Each color will add different scores.
It's time to see an abstract class in action:
public abstract class GameCoin { public abstract Integer coinValue(); public Integer absorbCoin(Integer existingPoint){ return existingPoint + coinValue(); } }
The coinValue
method is declared using the abstract
keyword, which means that all child classes need to implement this. However, it is known that whatever this method returns, it needs to be added to the existing points; and therefore, the absorbCoin
method does not need to be written again and again in all child classes. Don't get confused about how we have used an abstract method in absorbCoin
. Like interfaces, we cannot instantiate an abstract class; therefore, whenever absorbCoin()
is called from a child class, it will be implemented.
Let's play it out:
public class BlueCoin extends GameCoin{ public override Integer coinValue(){ return 50; } } public class YellowCoin extends GameCoin{ public override Integer coinValue(){ return 10; } }
The preceding two child classes extend the GameCoin
abstract class.
The anonymous Apex code for testing is as follows:
Integer totalPoints = 0; GameCoin coins = new BlueCoin(); totalPoints = coins.absorbCoin( totalPoints); coins = new YellowCoin(); totalPoints = coins.absorbCoin(totalPoints); coins = new BlueCoin(); totalPoints = coins.absorbCoin(totalPoints); System.debug('Total points - ' + totalPoints);
The output of this code will be as follows:
Total points - 110
The following class diagram shows two classes that extend an abstract class and implement an abstract method.

We all learn programming by making mistakes and learning from all the erroneous code that we develop. There will be situations where you may have faced a particular problem multiple times. Now, we have a clear approach on how to address the issue. A design pattern is designed, implemented, and verified industry wide.
Design patterns not only bring standardization to your code, but also ensure that your code follows good programming principles, such as coupling and cohesion.
Coupling measures the dependency of software components on each other. So, in essence, this is how two components interact with each other and pass information. High coupling leads to complex code. Practically, components need to communicate with each other, so dependency cannot be entirely removed. It also indicates the robustness of the code, that is, the impact it has on a component if any related component is modified. Hence, low coupling indicates a good code structure. Just imagine that you have a controller that calls a service class, which further calls another controller. So, effectively, the first controller is indirectly dependent on the second controller. With high coupling:
- Code maintenance can be tedious work
- Any change can have a ripple effect on the entire system
- There is less reusability of code

Cohesion measures the degree to which a code component has been well built and focused. As per object-oriented design principle, encapsulation, all the related data and functionalities should be encapsulated in the same program component (for example, a class). It ensures that all related functionalities are present in one place and controls their accessibility. This enhances the robustness of the code and imparts modularity to the final product. Lower code cohesion indicates lower dependency of modules/classes, that is, higher maintainability, less complexity, and lesser impact on the part of change.
In short, high cohesion is better for you and indicates that a class is doing a well-defined job. Low cohesion means that a class is doing many jobs with little in common between jobs.
The following code snippet is an example of high cohesion:
class AccountService{ public Account createAccount(){ // business logic } public Opportunity createOpportunity(){ // business logic } public Contact createContact(){ // business logic } }
In the preceding code snippet, notice that the AccountService
class tends to be a jack of all trades, that is, it tries to solve multiple objectives. This leads to further confusion between method calls and makes maintenance tedious.
The following code snippet is an example of low cohesion:
class AccountService{ public Account createAccount(){ // business logic } } class OpportunityService public Opportunity createOpportunity(){ // business logic } } class ContactService public Contact createContact(){ // business logic } }
The following diagram shows how we converted low cohesion to high cohesion.

Another advantage of using design patterns is that if testers know that a specific design pattern is used in an implementation, they can quickly relate to it. According to their past experience with design patterns, they can easily identify possible failure scenarios.
Next in the list of advantages is communication and support. Design patterns are well-known in the developer community and forums. Also, they can be easily discussed with your technical lead, project manager, test lead, or architects. When someone new joins your development team, usage of design patterns can help describe the code base to the new team member and aid in a developer's ramp up and acclimation.
Apex is a proprietary programming language for Salesforce and, therefore, is different from other programming languages, such as Java, C#, and C. Even though the syntax of Apex resembles to Java and C#; however, programming on the Force.com platform is quite different. We will discuss many standard design patterns in the next section of this chapter; however, every pattern may not be suitable for Apex.
A few important differences between Apex and other Object-Oriented Programming (OOP) languages are as follows:
- Apex runs on the multi-tenant platform; therefore, in order to make sure that other tenants are not impacted, Salesforce enforces various limits. As developers, we need to make sure that our code does not breach any governor limits.
- Other programming languages do not mandate code coverage for deployments. However, in the case of Salesforce, the Apex code needs to have a minimum code coverage of 75% (the entire code in the environment) for production deployments.
- Static variables in Java persist until the Java Virtual Machine (JVM) execution lifespan, which may last from days to months or even years. In the case of Apex, a static variable lasts for the duration of an individual user request execution only (until the time the user request is being processed on a server).
Note
Governor limits are Salesforce's way to force programmers to write efficient code. As Apex runs in a multitenant environment, a strict enforcement of all limits becomes a necessity for the Apex runtime engine so that no code monopolizes the shared resources. If because of a bad design or nonrecommended architecture, any code does not comply with governor limits, the Apex runtime throws a runtime exception, which cannot be handled within Apex. Apex also exposes many limit methods to check the limit consumption. Read more about this in detail at https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_limits.htm.
Design patterns in computer science achieved prominence when Design Pattern: Elements of Reusable Object-Oriented Software was published in 1994 by authors Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. These authors are also known as the Gang of Four (GoF).
This book contains 23 classic design patterns. After this book, many programmers adopted and created their own design patterns, referring to these classic patterns as bases.
Instead of memorizing exact classes, methods, and properties in design patterns, it is very important to understand the concept and where to apply it appropriately. Incorrect, unsuitable, or unnecessary usage of design patterns can over complicate your code and may result in code that is hard to maintain and debug.
Note
A design pattern is a tool. As with any tool, its performance depends on its usage and the user who is using it.
Gang of Four design patterns are divided into the following three categories:
- The creational pattern
- The structural pattern
- The behavioral pattern
The following figure shows a summary of the design patterns and their categories:

SOLID is short for basic five principles of OOP, which was introduced in the early 2000s and adopted widely in the software industry. When these principles are combined together, a programmer can create an application that will be easy to maintain and can be extended over time.
The SOLID abbreviation is defined as follows:
- S: Single responsibility principle
- O: Open closed principle
- L: Liskov substitution principle
- I: Interface segregation principle
- D: Dependency inversion principle
This states that a class should have only one reason to change it, and this means, it should have a single job.
If we can write code for multiple functionalities in a class, it doesn't mean that we should. Smaller classes and smaller methods will give us more flexibility, and we don't have to write a lot of extra code. It saves us from over complicating classes and helps in achieving high cohesion.
For example, the Person
class has the code to show the available balance and deduct it from Account
. This is a clear violation of SRP. This class has two reasons to change: if any attribute of Person
changes or any information about Account
changes.
The advantages of SRP are as follows:
- It makes code as easy as possible to reuse
- Small classes can be changed easily
- Small classes are more readable
Splitting classes is a way to implement SRP. Another example of the SRP violation is God classes, which we will discuss in the next chapter.
This states that entities of software, such as classes and methods, should be open for extension but closed for modification. This means that classes and methods should be allowed to be extended without modification.
For example, a class returns report data in the string and XML formats. In future, we may want to return data in the JSON or CSV format. We should not modify the existing class as it may have an impact on all the other classes using it. It would be a violation of OCP.
The importance of OCP lies in the following scenarios:
- Any changes made in any existing code can potentially impact the entire system
- In some conditions, we cannot change code (the managed package in Apex), so OCP is implied
We can implement OCP using design patterns, such as the strategy pattern. In the preceding scenario, we can create an interface of the ReportData
type and different classes implementing that interface to return different report formats. We will discuss this in more detail in the upcoming chapters.
This states that if class B is a child of class A, then A can be replaced by B, without changing anything in a program. In other words, the LSP principle states that you should not encounter unexpected results if child (derived) classes are used instead of parent classes.
This principle is also known as Substitutability and was introduced by Barbara Liskov in 1987. This is one of the most widely used principles in programming. You might be already using this, but may not know that it is called LSP.
For example, let's say that we have a Customer_Ticket
class defined to close a case using the close()
method. A Customet_Ticket_Escalated
child class is defined as well to handle an escalated case; however, it cannot close a case by a normal process because the customer was not happy. If we substitute a parent class by this child class and call the close()
method, it will throw an exception, which is a clear violation of LSP.
The following code snippet explains this scenario:
public virual class Customer_Ticket{ String status ; public virtual void close(){ status = 'close'; } //other code } public class Customet_Ticket_Escalated extends Customer_Ticket{ public override void close(){ throw new Exception('As this is escalated case therefore cannot be closed by normal process'); } //other code }
The anonymous Apex code for testing is as follows:
Customer_Ticket issue = new Customet_Ticket_Escalated(); issue.close();//runtime exception, violation of LSP
To implement LSP, a proper use of inheritance with a protected access specifier is needed, and a parent class should not have any attributes, which may not apply to every child class.
This states that do not force a child class to depend on a method that is not used for them. This principle suggests that you break interfaces into smaller ones so that a client can only implement an interface that is of interest. This principle is very similar to the high cohesive principle, as discussed earlier.
One way to identify the ISP violation is if we implement any interface or derive a base class where we need to throw an exception for an unsupported operation.
The ISP are as follows:
- It enforces the single responsibility principle for interfaces and base classes
- Any changes made in the interface may affect child classes even though they are not using unused methods
For example, Product
is an interface and contains the Name
and Author
attributes. Two child classes named Movie
and Book
are derived from Product
. However, Movie
is a Product
but does not have an author, and therefore a runtime exception would be thrown if it's used.
The following example shows the valid and invalid code according to the ISP:
Violation of ISP |
Adheres ISP |
Public interface Product{ Public String getName(); Public String getAuthor(); } Public Class Movie implements Product{ private String movieName; private String author; Public String getName(){ return movieName; } Public String getAuthor(){ return new CustomException('Method not Supported'); } }
Anonymous apex code for testing is as follows:
Product m = new Movie(); m.getAuthor();//runtime exception
|
Public interface Product{ Public String getName(); Public String getAuthor(); } Public Class Book implements Product{ private String bookName; private String author; Public String getName(){ return bookName; } Public String getAuthor(){ return author; } }
Anonymous apex code for testing is as follows:
Product p = new Book(); p.getAuthor(); //works
|
This states that modules should not depend on each other directly and should depend via an interface (abstraction).
In other words, two classes should not be tightly coupled. Tightly coupled classes cannot work independently of each other, and if a change is required, then it creates a wave of changes throughout the application.
One way to identify a DIP violation is the use of a new keyword in the same class. If we are using a new keyword, then this means that we are trying to instantiate a class directly. We can create a container class to delegate the creation of a new object. This class will know how to instantiate another class on the basis of the interface type. This approach is also known as dependency injection or Inversion of Control (IoC). If you know about the trigger factory pattern that is widely used in Apex, then you may be able to relate with it, else we will discuss this in the upcoming chapters.
For example, in the real world you would not want to solder a lamp directly to the electrical wiring; we would rather use a plug so that the lamp can be used in any electric outlet. In this case, the lamp and electric outlet are the class and the plug is the interface.
Class A should not know any details about how class B is implemented. An interface should be used for communication. As discussed earlier, if needed we can always create a new child class from the interface and use it as per the LSP principle.
The following screenshot shows a scenario before and after DIP. In the first case, the Apex scheduler directly uses classes to calculate sharing and assigns a record to the user. All three classes are tightly coupled in this case. As per DIP, we need to introduce interfaces between them so that classes do not depend on implementation, but they will depend on the abstraction (interface).

Tip
Downloading the example code
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
- Log in or register to our website using your e-mail address and password.
- Hover the mouse pointer on the SUPPORT tab at the top.
- Click on Code Downloads & Errata.
- Enter the name of the book in the Search box.
- Select the book for which you're looking to download the code files.
- Choose from the drop-down menu where you purchased this book from.
- Click on Code Download.
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
- WinRAR / 7-Zip for Windows
- Zipeg / iZip / UnRarX for Mac
- 7-Zip / PeaZip for Linux
The advantages of DIP are as follows:
- Tight coupling is bad and everyone knows this
- It's harder to write test classes as implementation details need to be known for other dependent classes
- If DIP is followed, fake test records can be supplied to classes directly without knowing the implementation details
In this chapter, we discussed design patterns and why we need their categories and types. In the next chapter, we will discuss the common challenges faced while creating objects and their solutions using design patterns. So, basically, the next chapter will focus completely on creational design patterns.