Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Apex Design Patterns
Apex Design Patterns

Apex Design Patterns: Harness the power of Apex design patterns to build robust and scalable code architectures on the Force.com platform

eBook
$27.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Apex Design Patterns

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:

OOPs in play

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:

An 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.

An abstract class

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

Advantages of design patterns

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.

Advantages of design patterns

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:

Gang of Four (GoF)

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).

The dependency inversion principle (DIP)

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.

Left arrow icon Right arrow icon

Key benefits

  • Apply Creational, Structural and behavioural patterns in Apex to fix governor limit issues.
  • Have a grasp of the anti patterns to be taken care in Apex which could have adverse effect on the application.
  • The authors, Jitendra Zaa is a salesforce MVP and Anshul Verma has 12+ years of experience in the area of application development.

Description

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

Who is this book for?

If you are a competent developer with working knowledge of Apex, and now want to deep dive into the world of Apex design patterns to optimize the application performance, then this book is for you. Prior knowledge of Salesforce and Force.com platform is recommended.

What you will learn

  • Apply OOPs principal in Apex to design a robust and efficient solution to address various facets to a business problem
  • Get to grips with the benefits and applicability of using different design patterns in Apex
  • Solve problems while instantiating, structuring and giving dynamic behavior to Apex classes
  • Understand the implementation of creational, structural, behavioral, concurrency and anti-patterns in your application
  • Follow the Apex best practices to resolve governor limit issues
  • Get clued up about the Inheritance, abstract classes, polymorphism in Apex to deal with the object mechanism
  • Master various design patterns and determine the best out of them
  • Explore the anti patterns that could not be applied to Apex and their appropriate solutions

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 27, 2016
Length: 256 pages
Edition : 1st
Language : English
ISBN-13 : 9781782173656
Vendor :
Salesforce
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Apr 27, 2016
Length: 256 pages
Edition : 1st
Language : English
ISBN-13 : 9781782173656
Vendor :
Salesforce
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 163.97
Force.com Enterprise Architecture
$65.99
Learning Apex Programming
$48.99
Apex Design Patterns
$48.99
Total $ 163.97 Stars icon
Banner background image

Table of Contents

6 Chapters
1. An Introduction to Apex Design Pattern Chevron down icon Chevron up icon
2. Creational Patterns Chevron down icon Chevron up icon
3. Structural Patterns Chevron down icon Chevron up icon
4. Behavioral Patterns Chevron down icon Chevron up icon
5. Handling Concurrency in Apex Chevron down icon Chevron up icon
6. Anti-patterns and Best Practices Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7
(9 Ratings)
5 star 66.7%
4 star 33.3%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Tilak Raj Jun 06, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very good book for intermediate developer
Amazon Verified review Amazon
Crista Jul 14, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you are a salesforce developer and you are looking to improve your skills this is a must buy.
Amazon Verified review Amazon
Major Jan 19, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a must have for any serious Developers as it addresses some of today's businesses' biggest challenges, code maintenance. With the wave of third party development companies are engaging, each solution will likely have to understand the design patterns and anti patterns. If they are unable to do so there is a tendency to isolate and create bigger issues for future application extensibility
Amazon Verified review Amazon
Kshitij Shah Jun 25, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
One of the best books on Apex Development that explains the concepts and best practices to be followed in a very precise manner. Also it includes sample examples that easily helps to understand the various design patterns.I recommend it for all Salesforce Developers and enthusiasts.
Amazon Verified review Amazon
Honest Reviews Mar 24, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Lots of cool information
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.