
Apex Design Patterns
Description
Alles über E-Books | Antworten auf Fragen rund um E-Books, Kopierschutz und Dateiformate finden Sie in unserem Info- & Hilfebereich.
Key Features
[*]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.
Book DescriptionApex 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 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
Who this book is forIf 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.
More details
Other editions
Additional editions

Persons
Anshul Verma has been working on the Salesforce platform since 2006. Prior to that, he has done extensive development using MS technologies on web, desktop, and mobile applications. He possesses a tremendous understanding of enterprise-scale systems and has worked in designing intricate systems with high scalability, performance, and robustness. He has been a Dreamforce speaker and is a regular contributor to Stack Exchange and other developer communities. He has four Salesforce certifications and is currently working as a project manager and technical architect where he is responsible for managing customer success and delivering high-quality solutions to his clients. He has conducted various training sessions in his current organization and trained over 50 new hires. He is very popular with his training batches and can be often found sharing his knowledge with his team and peers. He owns and maintains his blog (http://mightycoder.blogspot.com/), and you can follow him on Twitter at @toanshulverma.Zaa Jitendra :
Jitendra Zaa has been working on the Salesforce platform since 2008. He has extensively worked on Java and .NET-based enterprise applications. He also has experience in working with multiple JavaScript libraries, web frameworks, ETL tools, and databases. He is an expert in designing and implementing integrations of Salesforce with external systems. He is a regular speaker at the worlds biggest developer event, Dreamforce, mostly in developer track. Because of his contributions to the Salesforce community, he has also been awarded the Salesforce MVP title. He has more than eight Salesforce certifications and works as a Salesforce technical architect. He owns one of the most viewed Salesforce developer blogs (http://www.JitendraZaa.com), formerly, http://Shivasoft.in. You can follow him on Twitter at @JitendraZaa.
Content
"Need for design patterns"
"Creational Design Patterns"
"Structural Design Patterns"
"Behavioural Design Patterns"
"Concurrency Patterns"
"Anti Patterns"
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 LSPTo 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(); //worksThe 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...
System requirements
File format: ePUB
Copy protection: Adobe-DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Install the free reader Adobe Digital Editions prior to download (see eBook Help).
- Tablet/smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook before downloading (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (not Kindle).
The file format ePub works well for novels and non-fiction books – i.e., „flowing” text without complex layout. On an e-reader or smartphone, line and page breaks automatically adjust to fit the small displays.
This eBook uses Adobe-DRM, a „hard” copy protection. If the necessary requirements are not met, unfortunately you will not be able to open the eBook. You will therefore need to prepare your reading hardware before downloading.
Please note: We strongly recommend that you authorise using your personal Adobe ID after installation of any reading software.
For more information, see our ebook Help page.