Advanced Apex Programming in Salesforce 5th Edition Dan Appleman instant download
Advanced Apex Programming in Salesforce 5th Edition Dan Appleman instant download
https://ebookmeta.com/product/advanced-apex-programming-in-
salesforce-5th-edition-dan-appleman/
https://ebookmeta.com/product/the-apex-shifter-complete-set-apex-
shifter-1-3-1st-edition-emilia-hartley/
https://ebookmeta.com/product/functional-programming-
in-r-4-advanced-statistical-programming-for-data-science-
analysis-and-finance-second-edition-thomas-mailund/
https://ebookmeta.com/product/oversubscribed-how-to-get-people-
lining-up-to-do-business-with-you-2nd-edition-daniel-priestley/
Sol Cycle 1st Edition Kimberly Cooper Griffin
https://ebookmeta.com/product/sol-cycle-1st-edition-kimberly-
cooper-griffin/
https://ebookmeta.com/product/jci-accreditation-standards-for-
hospitals-6th-edition-english-version-soft-cover-joint-
commission-resources/
https://ebookmeta.com/product/the-benzodiazepines-crisis-the-
ramifications-of-an-over-used-drug-class-1st-edition-john-f-
peppin/
https://ebookmeta.com/product/ethos-logos-and-perspective-
studies-in-late-byzantine-rhetoric-first-edition-florin-leonte/
https://ebookmeta.com/product/a-n-whitehead-s-thought-through-a-
new-prism-1st-edition-aljoscha-berve/
Practical Strategies in Geriatric Mental Health Cases
and approaches 1st Edition Laura B. Dunn
https://ebookmeta.com/product/practical-strategies-in-geriatric-
mental-health-cases-and-approaches-1st-edition-laura-b-dunn/
Advanced Apex Programming in Salesforce
Fifth Edition
By
Dan Appleman
Desaware Publishing
ISBN: 978-1-936754-15-1
www.AdvancedApex.com
Table of Contents
Introduction
Sample Code
2 – Static Variables
3 – Limits
4 – Bulk Patterns
6 – Triggers
7 – Going Asynchronous
8 – Concurrency
9 – Application Configuration
11 – Unit Tests
Conclusion
Acknowledgements
I just wanted to get that out of the way. I know there is sometimes value in
the kind of book where 90% of the content is a rephrasing of the
documentation and only 10% is new and interesting – a good author can
organize information to make it easier for beginners to learn. But they are
frustrating for intermediate and advanced developers who have to sift
endlessly through familiar content to find one or two nuggets of new
material.
So I’m going to assume that you either have read, or can read, the Salesforce
Apex language documentation. If you are new to Apex, you will find this
book helpful – especially if you are coming to Apex from another language,
but it is not a tutorial and will not replace the Apex documentation. If you
have Apex programming experience, I’m confident you’ll find material here
that will at the very least prove thought provoking, if not occasionally mind-
blowing.
This book is about design patterns, best practices, and creative solutions to
the kinds of problems developers face out in the real world.
If you want to bring together real-world experience in a format that allows for
as much depth as necessary, and organizes the information in such a way that
concepts build on each other to really teach the material – you need a book.
You need a book written by someone who actually writes production code,
both as a consultant for individual clients, and as a developer of applications
for distribution.
About eleven years ago, I joined her and two others to establish a new
company, Full Circle Insights, to develop a new Salesforce application
related to marketing and sales data and analytics. As CTO, I designed and
built the application – which evolved into a very large and sophisticated
native AppExchange app (an app that runs entirely on the Force.com
platform). In doing so, I learned a lot.
As I have always enjoyed sharing what I learn, I ended up writing this book.
It contains all of the things that I wish I had known eight years ago when I
first started working in Apex. Things that I learned the hard way. Things that
are either not found in the documentation, or are hidden in a footnote
somewhere when they should be plastered across an entire page in bold
flashing neon.
Parts of this book focus on concepts – ways of thinking that will be fairly
easy to follow, even for relative beginners and those completely new to
Apex. But parts of this book focus more on advanced design patterns, and to
really understand them, you’ll need to dig into the code, and preferably install
and experiment with the samples. You may need to refer back to the language
documentation. You may even find parts of the book to be too hard to follow
on a first reading. In truth, the book would hardly deserve the word
“Advanced” in the title if this were not the case. If you do find yourself
getting stuck, skip or scan a section and then move on. You’ll find it easier to
digest the second time through.
By the time you’re done, I think you will find it was well worth the effort.
Dan Appleman
dan@desawarepublishing.com
Note to Readers of Previous
Editions
The Salesforce platform is updated three times a year. Some of the updates
are minor, some more significant, and some lead to radical changes in what
most would consider to be “best practices”. Best practices are tricky – you
can’t assume that just because something is new, it represents the best way to
do something.
Not only has the platform changed, but my own experience has changed – or
put another way, I keep learning as well. And since this is a book born of
real-world experience, those new experiences are reflected in each new
edition, along with those new platform features that seem truly useful.
In preparing this edition, I went through every word of text and every line of
code. Some of the changes are structural – I’ve tried to be more consistent in
naming conventions (while remaining true to my own belief that names
should be descriptive). Keep in mind that Apex is a case-insensitive
language, so any casing errors that may remain will not impact the
functionality of the examples. And while there are numerous changes
scattered throughout the text and code (this edition being more than 60 pages
longer than the previous one), here are the areas where the changes for this
edition were most significant:
Chapter 6: This chapter has been completely rewritten with all new examples
to incorpo-rate new technologies and modern approaches for refactoring
application functionality into decoupled applications or packages.
Chapter 7: The chapter and examples have been rewritten to address batch
apex exception events and queueable transaction finalizers. Other new topics
include the challenge of dealing with transactions in the context of callouts,
suicide scheduling and change data capture.
Chapter 10: The chapter and examples have been updated to be based on the
new trigger examples in chapter 6.
Chapter 12: Revised recommendations for unit tests and managed packages.
Salesforce DX represents both the future and today’s best practice for Apex
development, so my assumption is that anyone reading this book will be
either familiar with it, or ready to make that transition. If you are new to
Salesforce DX, there are numerous resources available to get started includ-
ing Trailhead and my Pluralsight course “Salesforce Development: Getting
Started”. I also assume that you have some basic familiarity with git. If you
are new to git, I encourage you to use a git UI such as SourceTree which
makes it easy to checkout branches and to see the files and changes in each
commit.
Finally, Salesforce has a habit of rebranding the platform for reasons that are
beyond my comprehension. When the third edition came out, “Force.com”
was in the process of becoming the “Salesforce Platform”. When the fourth
edition came out it was either the “Lightning Platform” or “Customer 360
Platform”. For the purposes of this edition, any of these terms are all used
interchangeably, though I’ll mostly use “Salesforce Platform”.
Sample Code
You can download the sample code for this book from the book’s website at
AdvancedApex.com/samplecode. It is provided as a directory containing a git
repository. Each branch contains a chapter in Salesforce DX format.
Each chapter may have one or more examples. Depending on the chapter,
progress through the examples is represented by commits which you can
check out to obtain the source code at that point in time. The commit
description will match the section in the book.
The sample code for some chapters includes a permission set named
“Advanced Apex” which you can assign to the current user to quickly obtain
access to fields or other elements used by the examples. In other cases, you
may need to explicitly set field or tab permissions.
For those who are not familiar with git, I recommend using Sourcetree
(https://www.sourcetreeapp.com), which is an excellent GUI on top of git.
You will need to install the sample code to follow some of the content in this
book – the book does not contain the complete listings of all the sample code.
About the Code Listings
This edition of Advanced Apex programming uses HTML formatted text for
listings. This is supported on all newer e-reader devices, but will result in a
poor experience on older devices that do not support a mono-spaced font.
Depending on your device, you may see code listings wrap in ways that make
them hard to read. In those cases you'll find that it is much easier to read the
listings if you place your device in landscape mode (supported on all newer
devices).
Ok, I know - that’s a stupid question to start with. Of course you know what a
computer language is. If you didn’t, you’d hardly be reading a book that
claims to be an advanced programming book.
At the same time, it’s a useful question for exactly that reason. Because you
do know what a computer language is, you’ll probably be grateful if I don’t
waste your time answering that question. In fact, it brings to mind a long list
of questions and introductory material that are not worth discussing at all,
either because you should know them, or because you can easily find them in
the documentation.
So let’s begin with a partial list of material that I won’t try to teach you.
Beyond Syntax
When we talk about computer languages in the context of actual software
development, we’re really talking about three different things:
Of these, this book will almost completely ignore the first item. If you’ve
used Apex at all, you’re probably well familiar with its syntax. If you are
migrating from another language, suffice to say that Apex is syntactically
similar to Java or C#, with most of the constructs you would expect from a
modern object-oriented language, including support for single inheritance and
interfaces.
Unlike Java or C#, Apex is not case sensitive. Some professional developers
are offended by this. Having years of experience in both C# and Visual Basic
(which is also not case sensitive), I’ll take the case insensitive language any
day. In my view, having to keep track of case is pointless labor, and anyone
who uses case to distinguish between two variables or language elements is
committing a mortal sin. But that’s just my opinion – yours may differ.
In terms of semantics, we’ll largely ignore the core language semantics. Most
of the language constructs: control flow structures, operators, variable
declarations, and so on, work exactly as you would expect. As of API 43, it
even has a Switch statement!
In fact, Apex is so similar to other languages, that at first glance you might
think that it will be a quick and easy migration. And in truth, it can be an easy
migration – but only if you recognize a few areas that are not only different,
but different in huge, fundamental ways.
Most of this book will be dealing with the third item on the list – the
interaction of the language with the platform. But the rest of this part of the
book will focus on the four key concepts that you must understand in order to
succeed in Apex programming:
Execution Contexts
Static Variables
Bulk Patterns
Limits
In a way, this is like learning a spoken language. You can memorize words
and phrases. But you don’t really know the language until you start thinking
and dreaming in it. My goal in this first part of the book is to help you take
the words and phrases that you know from the reference documentation or
other languages, and learn to think in Apex.
Exploring the Variety of Random
Documents with Different Content
Wohlwill, E., Galilei und sein Kampf für die kopernikanische Lehre.
I. Bd.: Bis zur Verurteilung der kopernikanischen Lehre durch die
römischen Kongregationen. 646 S. Hamburg und Leipzig,
Leopold Voß, 1910.
Verzeichnis der in Band IV enthaltenen
Abbildungen.
Figur aus
1. Bessel bestimmt die Parallaxe Bessel, Vorlesungen S. 251.
eines Fixsterns.
2. Grahams Dialysator. Annalen der Chemie und
Pharmazie, Bd. 121 (1862). Fig.
1.
3. Rudbergs Bestimmung des Poggendorffs Annalen, Bd. 41.
Ausdehnungskoeffizienten der S. 273.
Luft.
4. Gay-Lussacs Apparat zum Biot Traité de Physique Bd. 1. S.
Bestimmen der Dampfdichte. 291.
5. Dumas' Apparat zum Annales de Chimie et de
Bestimmen der Dampfdichte. Physique XXXIII. (1826). Fig. 1
auf S. 337.
6. Wheatstone erläutert das Wheatstone, Beiträge zur
binokulare Sehen. Physiologie der
Gesichtswahrnehmung. Tafel II.
Fig. 13. (Philos. Transact. 1838.
S. 371 bis 394.)
7. Wheatstones Stereoskop. A. a. O. Tafel I. Fig. 8.
8. Brewsters Stereoskop. Wüllner, Lehrbuch der
Experimentalphysik, Lpzg. B. G.
Teubner. Bd. II. (1875). S. 335,
Abb. 109.
9. Toeplers Schlierenapparat. A. Toepler, Beobachtungen nach
einer neuen optischen Methode.
Bonn 1864. Tafel I. Fig. 1.
10. Fizeaus Messung der Comptes rendus de l'Académie
Fortpflanzungsgeschwindigkeit des sciences XXIX, 90. 1849.
des Lichtes.
11. Faradays Nachweis der Poggendorffs Annalen. Bd. 25.
magnetischen Induktion. Tafel III. Fig. 1.
12. Faradays Nachweis der Poggendorffs Annalen. Bd 25.
Magnetinduktion. Tafel III. Fig. 2.
13. Faraday induziert Ströme in Ostwalds Klassiker der exakten
einer rotierenden Wissenschaften. Nr. 81. Fig. 7.
Kupferscheibe.
14. Luftthermometer zum Rieß, Die Lehre von
Nachweis des induzierten der Reibungselektrizität. Berlin
Stromes. 1853. Bd. I. Tafel 7. Abb. 97.
15. Faraday weist die Ostwalds Klassiker der
induzierende Wirkung des exakten Wissenschaften. Nr. 81.
Erdmagnetismus nach. Fig. 30.
16. Faradays Nachweis des Ostwalds Klassiker der exakten
Extrastroms. Wissenschaften Nr. 126 Fig. 1
17. Faradays Versuch über die Ostwalds Klassiker der
Entladung durch Gase. exakten Wissenschaften. Nr.
128. Fig. 2.
18. Faraday untersucht die Ostwalds Klassiker der
chemische Wirkung der exakten Wissenschaften. Nr. 86.
Reibungselektrizität. Fig. 3.
19. Die erste magnetelektrische Gerland und Traumüller,
Maschine. Geschichte der physikalischen
Experimentierkunst. Leipzig
1899. Abb. 394.
20. Faradays Voltaelektrometer. Ostwalds Klassiker der exakten
Wissenschaften. Nr 87. Fig. 9.
21. Faradays Nachweis des Ostwalds Klassiker der exakten
elektrolytischen Wissenschaften. Nr. 87. Fig. 14.
Grundgesetzes.
22. Faraday entdeckt den Ostwalds Klassiker der exakten
Diamagnetismus. Wissenschaften. Nr. 140. Fig. 1.
23. Lenz mißt die durch den Poggendorffs Annalen LXI
Strom erzeugte Wärme. (1844). Tafel I. Fig. 10.
24. Temperaturdifferenzen durch Wüllner, Lehrbuch der
den elektrischen Strom. Experimentalphysik. Leipzig
1875. Bd. IV. Fig. 145.
25. Webers Tangentenbussole. Ostwalds Klassiker der
exakten Wissenschaften. Nr.
142. Fig. 1.
26. Webers Elektrodynamometer. Wüllner, Lehrbuch der
Experimentalphysik. Leipzig
1875. Bd. IV. Fig. 198.
27. Das zusammengesetzte Auge Leunis, Synopsis der Tierkunde.
der Insekten. II. Bd. 3. Aufl. Fig. 55.
28. Die Zellen der Chorda dorsalis Th. Schwann,
einer Plötze. Mikroskopische Untersuchungen.
1839. Tafel I. Fig. 4.
29. Joules Apparat zur Philosoph. Transactions von
Bestimmung 1850. Teil I. Tafel VII. Fig. 1 und
des mechanischen Äquivalents 9.
der Wärme.
30. Pasteurs Verfahren, die Keime Ostwalds Klassiker der exakten
aus der atmosphärischen Luft Wissenschaften. Bd. 39. Tafel I.
abzusondern. Fig. 1.
31. Die Entdeckung der Sachs, Lehrbuch der Botanik.
Schwärmsporen. Leipzig, W. Engelmann 1874.
Abb. 176.
32. Versuche über die Reizbarkeit Pfeffer, Pflanzenphysiologie Bd.
der Sinnpflanze. II. S. 236. Leipzig, W.
Engelmann 1881.
33. Webers Modell zur Ostwalds Klassiker der exakten
Erläuterung Wissenschaften. Bd. 6. Fig. 10.
der Wellenbewegung im
Blute.
34. Graphische Darstellung Ostwalds Klassiker der exakten
des Sekretionsdrucks und des Wissenschaften. Bd. 18. Fig. 5.
Blutdruckes.
35. Darstellung der sechs Ostwalds Klassiker der exakten
Kardinalpunkte des Auges. Wissenschaften. Bd. 147. Tafel I.
Fig. 2.
36. Die Entwicklung der Steenstrup, Über den
Ohrenqualle. Generationswechsel. Tab. I. Fig.
1-30.
37. Befruchtetes Archegonium. Sachs, Lehrbuch der Botanik.
Leipzig, W. Engelmann 1874.
Abb. auf S. 351.
38. Junges Sporogonium Sachs, Lehrbuch der Botanik.
eines Lebermooses. Leipzig, W. Engelmann 1874.
Abb. auf S. 352.
39. Schematischer Schmeil, Lehrbuch der
Längsschnitt durch den Zoologie. Leipzig. 1908. Abb. auf
Süßwasserpolypen. S. 514.
40. Einstülpung der einschichtigen Claus, Lehrbuch der Zoologie.
Keimblase von Amphioxus. Marburg 1883. Fig. 598 A, B, C.
B, C.
41. Schema zur Erläuterung der
Mendelschen Regeln.
42. Kekulés Benzolkern.
43. Kristalle des rechtsweinsauren
und des linksweinsauren
Natrium-Ammoniums.
44. Die Konstitution der
stereoisomeren Verbindungen.
45. Fraunhofers Zeichnung der Denkschriften der Münchener
von ihm im Sonnenspektrum Akademie von 1814/15. Tab.
gefundenen dunklen Linien. II. Fig. 5.
46. Das erste, von Kirchhoff und Ostwalds Klassiker der exakten
Bunsen konstruierte Wissenschaften. Bd. 72. Fig. 1.
Spektroskop.
47. Kirchhoff vergleicht das Kirchhoff, Untersuchungen über
Sonnenspektrum mit den das Sonnenspektrum, Berlin
Spektren irdischer Elemente. 1862. Tafel 1.
48. Bunsens und Kirchhoffs Eisenlohr, Lehrbuch der Physik.
verbessertes Spektroskop. 1863. Fig. 338.
49. Kirchhoffs Spektroskop mit Schellen, Die Spektralanalyse.
vier Prismen. Braunschweig. 1871. Fig. 53.
50. Bunsens und Roscoes Apparat Ostwalds Klassiker der exakten
zum Messen der chemischen Wissenschaften. Bd. 34. Nr. 2.
Wirkung des Lichtes.
51. Graphische Darstellung der Ostwalds Klassiker der exakten
photo-chemischen Wirkungen Wissenschaften. Bd. 38. Fig. 18.
des Spektrums.
52. Schematische Darstellung Groth, Physikalische
eines Polarisationsapparates. Kristallographie, Leipzig. Verlag
von W. Engelmann 1876. Fig.
51.
53. Das von Hess benutzte Ostwalds Klassiker der exakten
Kalorimeter. Wissenschaften. Bd. 9. Abb. auf
S. 7.
54. Pfeffers Osmometer. Pfeffer, Pflanzenphysiologie. Bd
I. Fig. 6. Leipzig. Verlag von W.
Engelmann 1881.
55. Die Elektrolyse des Wassers
nach Grotthuß.
56. Die Elektrolyse des Wassers Ostwalds Klassiker der
nach Grotthuß. exakten Wissenschaften. Bd. 21.
Fig. 1.
57. Die Elektrolyse des Wassers Ostwalds Klassiker der exakten
nach Hittorf. Wissenschaften. Bd. 21. Fig. 2.
58. Helmholtzsche Resonatoren Helmholtz, Die Lehre von den
zur Analyse des Klanges. Tonempfindungen. 2. Aufl. Fig.
16 a und b.
59. Schema des von Helmholtz Helmholtz, Physiologische Optik.
erfundenen Augenspiegels. 1868. Abb. 95.
60. Die physiologische Wirkung Helmholtz, Physiologische Optik,
der Spektralfarben nach 1868. Abb. 291.
Helmholtz.
61. Feddersens Nachweis der Ostwalds Klassiker der exakten
elektrischen Schwingungen. Wissenschaften. Bd. 166. Tafel
III. Abb. 15.
62. Schema des von Hertz Hertz, Gesammelte Werke. Bd.
benutzten Resonators. II. Fig. auf S. 43.
63. Hertz konzentriert die Grimsehl, Lehrbuch der Physik.
elektrischen Strahlen mit Hilfe Leipzig. 1909. Fig. 1067.
eines
parabolischen Hohlspiegels.
64. Hertz' Versuch über die Grimsehl, Lehrbuch der Physik.
Reflexion der elektrischen Leipzig 1909. Fig. 1068.
Strahlen.
65. Magnetische Kraftlinien. Grimsehl, Lehrbuch der Physik.
Leipzig. 1909. Fig. 682.
66. Der von Reis konstruierte Hennig, Die Entwicklung der
Empfänger. Telegraphie und Telephonie.
Leipzig 1908. Abb. 59.
67. Der Sprecher des von Reis Hennig, Die Entwicklung der
konstruierten Telephons. Telegraphie und Telephonie.
Leipzig. 1908. Abb. 58.
68. Schema zur Erläuterung
des dynamo-elektrischen
Prinzips.
69. Schema des elektrischen Moissan, Der elektrische Ofen.
Ofens. Deutsch von Zettel. Berlin. 1900.
Abb. 1.
70. Elektrischer Ofen im Betriebe. Moissan, Der elektrische Ofen.
Deutsch von Zettel. Berlin.
1900. Abb. 3.
Die Naturwissenschaften
in ihrer Entwicklung und in ihrem
Zusammenhange
dargestellt von Friedrich Dannemann.
Erster Band:
Zweiter Band:
Dritter Band:
Die vier Bände des Werkes sind einzeln käuflich. Jeder Band
bildet ein in sich abgeschlossenes Ganzes.
Updated editions will replace the previous one—the old editions will
be renamed.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.