Home Programming Apex Design Patterns

Apex Design Patterns

By Anshul Verma , Jitendra Zaa
ai-assist-svg-icon Book + AI Assistant
eBook + AI Assistant $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime! ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Along with your eBook purchase, enjoy AI Assistant (beta) access in our online reader for a personalized, interactive reading experience.
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime! ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
eBook + AI Assistant $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Along with your eBook purchase, enjoy AI Assistant (beta) access in our online reader for a personalized, interactive reading experience.
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
About this book
Apex is an on-demand programming language providing a complete set of features for building business applications – including data models and objects to manage data. Apex being a proprietor programming language from Salesforce to be worked with multi tenant environment is a lot different than traditional OOPs languages like Java and C#. It acts as a workflow engine for managing collaboration of the data between users, a user interface model to handle forms and other interactions, and a SOAP API for programmatic access and integration. Apex Design Patterns gives you an insight to several problematic situations that can arise while developing on Force.com platform and the usage of Design patterns to solve them. Packed with real life examples, it gives you a walkthrough from learning design patterns that Apex can offer us, to implementing the appropriate ones in your own application. Furthermore, we learn about the creational patterns that deal with object creation mechanism and structural patterns that helps to identify the relationship between entities. Also, the behavioural and concurrency patterns are put forward explaining the communication between objects and multi-threaded programming paradigm respectively. We later on, deal with the issues regarding structuring of classes, instantiating or how to give a dynamic behaviour at a runtime, with the help of anti-patterns. We learn the basic OOPs principal in polymorphic and modular way to enhance its capability. Also, best practices of writing Apex code are explained to differentiate between the implementation of appropriate patterns. This book will also explain some unique patterns that could be applied to get around governor limits. By the end of this book, you will be a maestro in developing your applications on Force.com for Salesforce
Publication date:
April 2016
Publisher
Packt
Pages
256
ISBN
9781782173656

 

Chapter 1. An Introduction to Apex Design Pattern

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.

 

Innovation


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.

 

Design patterns and learning


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.

 

Object-Oriented Programming (OOP)


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
 

OOPs in play


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.

Static and dynamic dispatch

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


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.

Note

Apex does not support multiple inheritance where one child class extends multiple parent classes at a time. However, using an interface a child class can implement multiple interfaces at a time.

 

An abstract class


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.

 

Advantages of design patterns


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.

 

Design patterns and Apex


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.

 

Gang of Four (GoF)


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:

 

The SOLID principle


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

The single responsibility principle (SRP)

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.

The open closed principle (OCP)

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.

The Liskov substitution principle (LSP)

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.

The interface segregation principle (ISP)

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

The dependency inversion principle (DIP)

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:

  1. Log in or register to our website using your e-mail address and password.
  2. Hover the mouse pointer on the SUPPORT tab at the top.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box.
  5. Select the book for which you're looking to download the code files.
  6. Choose from the drop-down menu where you purchased this book from.
  7. 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
 

Summary


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.

About the Authors
  • 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.

    Browse publications by this author
  • 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.

    Browse publications by this author
Latest Reviews (6 reviews total)
Achat d'un excellent produit.
everything was ok, quickly and without problems
Book covers the major design patterns and how to effectively apply them in the Salesforce.com platform.
Apex Design Patterns
Unlock this book and the full library FREE for 7 days
Start now