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
Mex$561.99 Mex$803.99
Paperback
Mex$1004.99
Subscription
Free Trial

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to Mexico

Standard delivery 10 - 13 business days

Mex$149.95

Premium delivery 3 - 6 business days

Mex$299.95
(Includes tracking information)

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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Mexico

Standard delivery 10 - 13 business days

Mex$149.95

Premium delivery 3 - 6 business days

Mex$299.95
(Includes tracking information)

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 Mex$85 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 Mex$85 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Mex$ 3,363.97
Force.com Enterprise Architecture
Mex$1353.99
Learning Apex Programming
Mex$1004.99
Apex Design Patterns
Mex$1004.99
Total Mex$ 3,363.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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela